- 字符串及其操作
- 字符串對象操作
- 字符串元素操作
- 轉義
- 查詢操作
- 字符串的操作
- 連接
- 分割
- 轉換
- 修改
- 查找
- 判斷
- s.startswith:判斷字符串是否以某個前綴開始,返回結果是bool
- s.endswith:end參數表示從索引end處停止比較
- s.isalnum:檢測字符串是否由字母或數字,多個空格都不行
- s.isdecimal:檢查字符串是否只包含十進制字符,這種方法只存在於unicode對象。
- s.islower:檢測字符串是否由小寫字母組成
- s.isspace:檢測字符串是否只由空格組成。
- s.isalpha:檢測字符串是否只由字母組成。
- s.isdigit:檢測字符串是否只由數字組成。
- s.isnumeric:檢測字符串是否只由數字組成,這種方法是隻針對unicode對象。
- s.istitle:檢測字符串中所有的單詞拼寫首字母是否爲大寫,且其他字母爲小寫。
- s.isascii:判斷字符串是否只包含ASCII字符
- s.isidentifier:用於判斷字符串是否是有效的Python標識符,可用來判斷變量名是否合法。
- s.isprintable:如果所有字符都是可打印的,則isprintable()方法返回True,否則返回False。不可打印的字符可以是回車和換行符。
- s.isupper:檢測字符串中所有的字母是否都爲大寫
字符串及其操作
字符串是集合類型, 並不是一個基本類型
字符串對象操作
新建字符串
- 方法1:s = 'hello python'
- 方法2:s = "hello python"
- 方法3:s = '''hello python'''
- 方法4:s = """hello python"""
前兩種完全一樣, 後兩種完全一樣
三引號可以定義多行字符串,單/雙引號只能定義單行字符串
方法3或方法4與方法1或方法2的區別:
In [42]: s = '''hello python
...: i like python'''
In [43]: s = 'hello python
File "<ipython-input-43-07b7eed529d4>", line 1
s = 'hello python
^
SyntaxError: EOL while scanning string literal
三引號可以定義多行字符串
單/雙引號只能定義單行字符串
刪除字符串對象
需要使用del方法刪除
截至2020年5月23日,本人暫時還未發現其他的方法
字符串元素操作
轉義
轉義字符(這裏的不全,可以互聯網搜索)
- \n:換行
- \t:製表符
- \r:回車
回車與換行區別:老式打印機
換行是紙帶往上移動一行。
回車是把針頭回到開始位置。
window是\n\r換行。unix是\n。
python3中加r前綴代表此字符串是自然字符串
In [47]: s = 'i like \npython'
In [48]: print(s)
i like
python
In [49]: s = 'i\'m comyn' #'有特殊作用,所以需要\'轉義一下
In [50]: print(s)
i'm comyn
三引號常用於:
sql = '''select * from `table` where name='comyn' '''
取消轉義場景
In [52]: path = 'c:\windows\nt\system32' # 正常情況顯示
In [53]: print(path)
c:\windows
t\system32
In [54]: path = 'c:\windows\\nt\system32' # 取消轉義
In [55]: print(path)
c:\windows\nt\system32
In [56]: path = 'c:\\windows\\system32' # 也可以將所有的都轉移,以防萬一。
In [57]: path = r'c:\windows\nt\system32' # 加r前綴代表此字符串是自然字符串, 不會轉義,python3中只有\r前綴。python2中有\u前綴。
In [58]: print(path)
c:\windows\nt\system32
In [59]: '\n' == '\r' # \n和\r是不相等的。
Out[59]: False
In [60]: print("123\r45") # \r回到起點,將12蓋掉了
453
python3中所有字符串都是unixcode
查詢操作
下標操作
- 字符串也支持下表操作
- 字符串是無法通過下標更改的
- 字符串是可迭代對象,也就是說可以作爲for循環的值
In [61]: s
Out[61]: "i'm comyn"
In [62]: s[3]
Out[62]: ' '
In [63]: s[4]
Out[63]: 'c'
In [64]: type(s[4])
Out[64]: str
In [65]: s[4] = C # 字符串是不可變的
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-65-a888c3296699> in <module>()
----> 1 s[4] = C
NameError: name 'C' is not defined
In [66]: s
Out[66]: "i'm comyn"
字符串是可迭代對象:
In [67]: for c in s:
...: print(c)
...:
i
'
m
c
o
m
y
n
字符串的操作
連接
str.join連接,將可迭代對象轉換爲字符串
注意:此操作會返回一個新的字符串對象,但不會操作原有可迭代對象
In [73]: lst = ['i', 'am', 'comyn']
In [74]: ' '.join(lst) # join是字符串的方法,參數是可迭代對象,接收者是分隔符
Out[74]: 'i am comyn'
In [76]: ','.join(lst)
Out[76]: 'i,am,comyn'
In [77]: ''.join(lst)
Out[77]: 'iamcomyn'
分割
分割:指定分隔符對字符串進行切片
split通過指定分隔符對字符串進行切片,返回一個list
- split默認使用空格分割
- 多個空格當成一個空格處理
- 當指定了以空格爲分割符時,每個空格都處理
- s.split(maxsplit=1) # 只分割一次,maxsplit參數表示分割多少次,默認是-1, 表示分割所有分隔符
- s.split('lo') # 分隔符可以是任意字符串
In [78]: s = 'i love python'
In [80]: s.split() # split默認使用空格分割
Out[80]: ['i', 'love', 'python']
In [81]: 'i love python'.split() # 多個空格當成一個空格處理
Out[81]: ['i', 'love', 'python']
In [82]: 'i love python'.split(' ') # 當指定了以空格爲分割符時,每個空格都處理
Out[82]: ['i', '', '', '', '', 'love', 'python']
In [83]: s.split(maxsplit=1) # 只分割一次
Out[83]: ['i', 'love python']
In [84]: 'i i i i i i i i i'.split(maxsplit=2) # split從左往右分割字符串, maxsplit參數表示分割多少次, 默認爲-1, 表示分割所有分隔符。
Out[84]: ['i', 'i', 'i i i i i i i']
In [85]: s.split('o') # 指定o爲分割符
Out[85]: ['i l', 've pyth', 'n']
In [86]: s.split('lo') # 分隔符可以是任意字符串
Out[86]: ['i ', 've python']
split的實現:
In [90]: def split(s, sep, maxsplit):
...: ret = []
...: tmp = []
...: i = ()
...: for c in s:
...: if c != sep:
...: tmp.append(c)
...: else:
...: i += 1
...: ret.append(''.join(tmp))
...: tmp.clear()
...: if maxsplit > 0 and i >= maxsplit:
...: ret.append()
...: return ret
...: return ret
rsplit
rsplit:是split從右往左的版本
In [87]: 'i i i i ii i i'.rsplit(maxsplit=1)
Out[87]: ['i i i i ii i', 'i']
In [88]: 'i i i i ii i i'.rsplit()
Out[88]: ['i', 'i', 'i', 'i', 'ii', 'i', 'i']
In [89]: 'i i i i ii i i'.split()
Out[89]: ['i', 'i', 'i', 'i', 'ii', 'i', 'i']
當不是用maxsplit參數時, split和rsplit表現形式一樣,但是split效率高於rsplit
rsplit的實現:
In [91]: def rsplit(s, sep, maxsplit):
...: ret = []
...: tmp = []
...: i = ()
...: for c in reversed(s):
...: if c != sep:
...: tmp.append(c)
...: else:
...: i += 1
...: ret.append(''.join(reversed(tmp)))
...: tmp.clear()
...: if maxsplit > 0 and i >= maxsplit:
...: ret.append()
...: return reversed(ret)
...: return reversed(ret)
splitlines:分割行
- 返回結果不會帶換行符
In [92]: s = ''' i am comyn
...: i love python'''
In [93]: s.splitlines() # 按行分割,並且返回結果不帶換行符
Out[93]: [' i am comyn', 'i love python']
In [94]: s.splitlines(True) # 按行分割, 並且返回結果帶換行符
Out[94]: [' i am comyn\n', 'i love python']
partition返回三元組
- 當要分割的內容爲空時,返回也爲空
- 當要分割的內容爲要返回的內容時, 除了sep, 其他都爲空
In [95]: 'i am comyn'.partition(' ') # 總是返回一個三元組, 它按傳入分割符分割一次,得到 head tail, 返回結果是head, sep, tail。(sep是指分隔符)
Out[95]: ('i', ' ', 'am comyn')
partition的實現:
In [103]: def partition(s, sep):
...: if s == '':
...: return '','',''
...: tmp = s.split(sep, mapsplit=1)
...: if len(tmp) == 2:
...: return tmp[0], sep, tmp[1]
...: if len(tmp) == 1:
...: return tmp[0], sep, ''
...: if len(tmp) == 0:
...: return '', sep, ''
rpartition
rpartition:是partition從右往左的版本
In [96]: cfg = 'mysql.connect = mysql://user:[email protected]:3306/test'
In [97]: cfg.partition('=')
Out[97]: ('mysql.connect ', '=', ' mysql://user:[email protected]:3306/test')
In [98]: cfg = 'env = PATH=/usr/bin:$PATH'
In [99]: cfg.partition('=')
Out[99]: ('env ', '=', ' PATH=/usr/bin:$PATH')
In [100]: ''.partition('=') # 當要分割的內容爲空時,返回也爲空
Out[100]: ('', '', '')
In [101]: '='.partition('=') # 當要分割的內容爲要返回的內容時, 除了sep, 其他都爲空
Out[101]: ('', '=', '')
轉換
經常用在英文書寫格式上面,比如首字母大寫。
In [104]: s = 'test'
In [105]: s.upper() # 全部轉換爲大寫
Out[105]: 'TEST'
In [106]: s.upper().lower() # 先轉換爲大寫,然後轉換爲小寫
Out[106]: 'test'
In [107]: s.title() # 首字母轉換爲大寫
Out[107]: 'Test'
In [108]: s.capitalize() # 首字母轉換爲大寫
Out[108]: 'Test
In [109]: 'i love python'.title() # 與capitalize的區別, title常用於標題
Out[109]: 'I Love Python'
In [110]: 'i love python'.capitalize() # 與title的區別, 常用於正文
Out[110]: 'I love python'
In [111]: s.center(80) # 標題居中
Out[111]: ' test '
In [112]: s.zfill(80) # 居右,用0填充
Out[112]: '0000000000000000000000000000000000000000000000000000000000000000000000000000test'
In [117]: s.casefold() # 原地返回
Out[117]: 'test'
In [118]: 'Test TTset'.casefold() # 使用大小寫不同的測試, 全轉換爲大寫或小寫, 不同的平臺有不同的表現形式, 但是同一個平臺下, 表現形式相同, 通常用來忽略大小寫的比較。忽略大小寫。
Out[118]: 'test ttset'
In [119]: s.swapcase() # 大小寫互換
Out[119]: 'TEST'
In [120]: 'Test'.swapcase() # 大小寫互換
Out[120]: 'tEST'
In [121]: '\t'.expandtabs(4) # 將table製表符轉換爲空格
Out[121]: ' '
In [123]: s.format() # 單獨講,變化非常多,非常常用。
Out[123]: 'test'
upper:全部轉換爲大寫
lower:全部轉換爲小寫
title:標題,首字母大寫
capitalize:首字母大寫,常用於正文
center:標題居中
zfill:標題居右, 用0填充
casefold:忽略大小寫
swapcase:大小寫互換
expandtabs:將table製表符轉換爲空格
修改
In [124]: s = 'i love python'
In [125]: s.replace('love', 'give up') # 返回新字符串,使用new替換old
Out[125]: 'i give up python'
In [127]: s = 'i very very love python'
In [128]: s.replace('very', 'not') # 有多少個替換多少個
Out[128]: 'i not not love python'
In [129]: s.replace('very', 'not', 1) # 可選的count參數,指定替換多少次
Out[129]: 'i not very love python'
replace只能從前往後替換
In [130]: s = ' hahahahahah haha '
In [131]: s.strip() # strip移除字符串前後的空格
Out[131]: 'hahahahahah haha'
In [132]: s = '\n \r \t hahaha \t \n \r'
In [133]: s.strip() # strip移除前後的空白字符
Out[133]: 'hahaha'
注意:空格和空白是不一樣的概念
In [135]: s = '######haha #### haha #####'
In [136]: s.strip('#') # 指定移除字符
Out[136]: 'haha #### haha '
In [138]: s = '{{ haha }}'
In [139]: s.strip('{}') # 指定移除多個字符
Out[139]: ' haha '
In [140]: s.strip('{} ') # 多加個空白,移除空白字符
Out[140]: 'haha'
In [141]: s.lstrip('{} ') # lstrip表現和strip一樣,但是隻處理左端
Out[141]: 'haha }}'
In [142]: s.rstrip('{} ') # rstrip表現和strip一樣,但是隻處理右端
Out[142]: '{{ haha'
In [143]: s = 'test'
In [144]: s.ljust(10) # 原串在左邊
Out[144]: 'test '
In [145]: s.rjust(10) # 原串在右邊
Out[145]: ' test'
In [146]: s.center(10) # 原串在中間
Out[146]: ' test '
In [147]: s.center(10, '#') # 原串在中間,使用指定字符填充
Out[147]: '###test###'
In [148]: s.ljust(10, '#') # 原串在右邊,使用指定字符填充
Out[148]: 'test######'
In [149]: s.center(10, '##') # 填充字符串長度只能爲1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-149-6e82a3cbddcf> in <module>()
----> 1 s.center(10, '##')
TypeError: The fill character must be exactly one character long
In [150]: s.center(3) # 如果寬度小於等於原串長度,不做任何操作
Out[150]: 'test'
In [152]: s.center(11, '#') # 優先填充左邊
Out[152]: '####test###'
replace:替換, 全替換
strip:移除字符串前後的空格
lstrip:移除左端的字符
rstrip:移除右端的字符
center:居中, 可以使用隨意字符串填
ljust:原串在左邊
rjust:原串在右邊
查找
In [155]: s = 'i love python'
In [156]: s.find('love') # 從左往右查找,找到第一個字串love,返回字串首字母的索引
Out[156]: 2
In [157]: s.find('love1') # 當字串不存在時,返回-1
Out[157]: -1
In [158]: s = 'i very very love python'
In [159]: s.find('very') # 當有多個值的時候,返回第一個
Out[159]: 2
In [160]: s.find('very', 3) # start參數指定從哪裏開始查找
Out[160]: 7
In [161]: s.find('very', 3, 5) # end參數指定到哪裏結束查找, end不包含
Out[161]: -1
In [162]: s.rfind('very') # rfind是find從右往左的版本
Out[162]: 7
In [163]: s.rfind('very', 3) # start和stop意義一樣,事實上, 是先根據start和stop截取字符串,再查找
Out[163]: 7
In [164]: s.rfind('very', 8)
Out[164]: -1
In [165]: s.index('very') # 幾乎與find一模一樣
Out[165]: 2
In [166]: s.index('very', 3)
Out[166]: 7
In [167]: s.index('very', 8) # 不存在的拋出ValueError, find查找不存在的時候返回-1, index和find惟一區別。
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-167-c5dce18db14c> in <module>()
----> 1 s.index('very', 8)
ValueError: substring not found
In [3]: s.rindex('very') # rindex是index從右往左的版本
Out[3]: 7
In [5]: s.count('very') # 存在
Out[5]: 2
In [6]: s.count('haha') # 不存在返回0
Out[6]: 0
In [7]: s.count('very', 3) # 從第三個開始統計
Out[7]: 1
s.find:查找, 從左至右
s.rfind:查找, 從右至左
s.index:根據值找出位置
s.rindex:是index的從右至左的版本
s.count:統計關鍵詞出現的次數
判斷
In [8]: s.startswith('i very') # 判斷字符串是否以某個前綴開始,返回結果是bool
Out[8]: True
In [9]: s.startswith('abc')
Out[9]: False
In [10]: s.startswith('very', 2) # start參數表示的是從索引start處開始比較
Out[10]: True
In [11]: s.startswith('very', 2, 5) # end參數表示從索引end處停止比較
Out[11]: False
In [12]: s.endswith('python') # 判斷字符串是否以某個後綴結尾, 返回bool
Out[12]: True
In [3]: s.endswith('python', 17) # start參數表示從索引start處開始比較
Out[3]: True
In [5]: s.endswith('python', 0, 22) # end參數表示到索引end爲止, 不包含end
Out[5]: False
In [6]: 'a'.isalnum() # 檢測字符串是否由字母和數字組成;
Out[6]: True
In [81]: s.isalnum() # 因爲s含有空格, 所以返回False
Out[81]: False
In [82]: s.isidentifier() # 字符是否是合法標示符
Out[82]: False
In [84]: 'abc_123'.isidentifier()
Out[84]: True
合法標示符:
字母或者下劃線開頭
僅包含字母數字和下劃線
In [9]: 'a'.isidentifier()
Out[9]: True
string模塊是補充自帶字符方法不夠的模塊;