在Python中字符串是不可變變量,對其進行切片及其中的元素復制都會報錯
>>>?str?=?"This?is?Python" >>>?str[0:3]?=?"abc" Traceback?(most?recent?call?last): ??File?"",?line?1,?in? TypeError:?'str'?object?does?not?support?item?assignment
其常用的方法:
-
split
用法:str.split(sep=None, maxsplit=-1)
將字符串劃分為序列
>>>?env?=?"/usr/bin/python" >>>?tmp_env?=?env.split("/") >>>?tmp_env ['',?'usr',?'bin',?'python']
-
replace
用法:str.replace(old,new[,max])
將指定子串替換為另一個子串,并返回替換后的結果, 但不會改變原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'
-
find
用法: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?"",?line?1,?in? 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
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
