在Python中字符串是不可變變量,對其進行切片及其中的元素複製都會報錯html
>>> str = "This is Python" >>> str[0:3] = "abc" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
其經常使用的方法:python
splitide
用法:str.split(sep=None, maxsplit=-1)spa
將字符串劃分爲序列code
>>> env = "/usr/bin/python" >>> tmp_env = env.split("/") >>> tmp_env ['', 'usr', 'bin', 'python']
replaceorm
用法:str.replace(old,new[,max])htm
將指定子串替換爲另外一個子串,並返回替換後的結果,但不會改變原String的內容索引
>>> str = "This are Python" >>> rep_str = str.replace("are","is") >>> rep_str 'This is Python' >>> str 'This are Python' >>> str = "This is Python,That is Great" >>> rep_str = str.replace("is","was",2) >>> rep_str 'Thwas was Python,That is Great'
findip
用法:str.find(sub[, start[, end]])文檔
在字符串中查找字串,若找到,則返回字串的第一個字符的索引,不然,返回-1
>>> str = "This is Python,Hello ,中國,您好" >>> fd_str = str.find("is") >>> fd_str 2 >>> str[fd_str] 'i' >>> fd_str2 = str.find("中") >>> str[fd_str2] '中' >>> str1 = "That is dog".find("G") >>> str1 -1
join
用法:str.join(iterable)
合併序列的元素
>>> dirs = ['','usr','bin','python'] >>> '/'.join(dirs) '/usr/bin/python' >>> num = [1,2,3,4] #合併數字列表,報錯 >>> seq = '+' >>> seq.join(num) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected str instance, int found >>> str1 = ["A","B","C"] #合併字符列表,OK >>> seq = "-" >>> seq.join(str1) 'A-B-C' >>> str1 = "ABCDE" >>> seq = "abcde" >>> seq.join(str1) 'AabcdeBabcdeCabcdeDabcdeE'
strip
用法:str.
strip
([chars])
將字符串開頭和末尾的空白(不包括中間的空白)刪除,並返回結果
>>> " Hello,World!".strip() 'Hello,World!' >>> "Hello,World ".strip() 'Hello,World' >>> " Hello,World ".strip() 'Hello,World' >>> "Hello, World! !".strip() 'Hello, World! !' >>> "www.baidu.com".strip("com") 'www.baidu.' >>> "www.baidu.com".strip(".com") 'www.baidu'
center
用法:str.
center
(width[, fillchar])
經過在兩邊填充字符(默認爲空格)讓string居中
>>> "0123456789".center(1) '0123456789' >>> "0123456789".center(-1) '0123456789' >>> "0123456789".center(10) '0123456789' >>> "0123456789".center(11) ' 0123456789' >>> "0123456789".center(11,"*") '*0123456789' >>> "0123456789".center(12,"*") '*0123456789*' >>> "0123456789".center(20,"*") '*****0123456789*****'
詳細的String參數可參考官網文檔:
https://docs.python.org/3.7/library/stdtypes.html?highlight=replace#str.replace