python (4)字符串

如果要查看. 后面加的東西要加teb teb

定義變量為字符串的操作

a1="line"
a2="qf"
a3="""hello lenovo"""
a4='''hello world'''
a5="""
hello world
"""
a6='''
hello world
'''

符號型的操作

轉(zhuǎn)義符:\
test='this shirt doesn\'t fit me'  #  ' 有特殊含義
word='hello \nshark'        #這個不是在python里面回車,而是在輸入文件后回車
拼接:+ 
print('hello' + 'lenovo')
'lenovo' +1     <報錯       #不是同一類型無法拼接
復(fù)制:*
print('*' * 20)
********************
print('lenovo 666'*20)  #輸出同上面一樣重復(fù)前面的字符打印
 >>> "hey"  * 0    #字符串 和 0 或者 負(fù)數(shù)相乘,會得到一個空字符串
''
>>> "hey"  * -100
''
>>>         

split分割

默認(rèn)空格字符或者tab鍵

\>>> ip ="192.168.18.18         sdjhf   a;f;l"   #會自定義的刪除多余的空格,縮進(jìn)
>>> ip.split()
['192.168.18.18', 'sdjhf', 'a;f;l']
>--------------------
>>> ip.split(" ")     #用來查看空白字符
['192.168.18.18', '', '', '', '', '', '', '', '', 'sdjhf', '', '', 'a;f;l']      
>-------------------------
自定義分割符
>>> ip.split(".")
['192', '168', '18', '18         sdjhf   a;f;l']

rsplit從右到左分割

從右到左分割,遇到第一個就分割一次;還可以自定義只分割幾個

>>> ip.rsplit('.',1)
['192.168.18', '18         sdjhf   a;f;l']   #從右到左分割第一個
>>> ip.rsplit('.',-1)         #從右到左分割全部;負(fù)數(shù)全分完
['192', '168', '18', '18         sdjhf   a;f;l']

replace替換

>>> url = "www.qfedu.com"
>>> url.replace(".","_")      #把. 替換成_
'www_qfedu_com'
>>> url.replace(".","_",1)   #可以只替換一個
'www_qfedu.com'

strip移除兩邊的空字符串

>>> s = ' shark '
>>> s.strip()
'shark'
>>> s
' shark '
>>> 
>----------------------------------------
>>> s.split(';')
['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC', '']
>>> s.split(';')[:-1]        #組合前面的字符串切片來看
['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC']

image.png

startswith判斷以什么開頭的:判斷正確錯誤

>>> s="I went win"
>>> s.startswith("I")
True 
>>> s.startswith("I we")  #可以匹配多個字符
True
>>> s.startswith("we")
False

endswith判斷字符串是以什么結(jié)尾的

和startswith是差不多的

>>> s ="ah auoh"
>>> s.endswith("d")
False
>>> s.endswith("h")
True

index獲取字符串中的索引號

>>> s ="ah auoh"    #有相同的會獲取第一個
>>> s.index('h')
1
>>> s = 'hello world'
>>> s.index('h')
0
>>> s.index('l')
2

a.capitalize() #字符串的首字母變大寫。其他字母小寫
a.title() #單詞首字母大寫
a.upper() #全部大寫
a.lower () #全部小寫

交互式輸入

n = input(">>>:")  #python3接收到的永遠(yuǎn)是字符串;python2輸入什么接收到的就是什么
print(n)
>------------------------------
>> import getpass         #開啟getpass模塊
>>> pwd =getpass.getpass("input passwords:")   #getpass里面的getpass函數(shù)
input passwords:
>>> print(pwd)
123

對于字符串和字節(jié)串類型來說,當(dāng)且僅當(dāng) x 是 y 的子串時 x in y 為 True。
空字符串總是被視為任何其他字符串的子串,因此 "" in "abc" 將返回 True。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容