>>?str?=? This?is?Python >>>?str[0:3]?=? abc Traceback?(most?recent?call?last): ..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python之字符串

發(fā)布時間:2020-06-27 16:26:45 來源:網(wǎng)絡(luò) 閱讀:356 作者:zjdevops 欄目:編程語言

在Python中字符串是不可變變量,對其進(jìn)行切片及其中的元素復(fù)制都會報錯

>>>?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

其常用的方法:

  • 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])

將指定子串替換為另一個子串,并返回替換后的結(jié)果,但不會改變原String的內(nèi)容

>>>?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]???#合并數(shù)字列表,報錯
>>>?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])

將字符串開頭和末尾的空白(不包括中間的空白)刪除,并返回結(jié)果

>>>?"??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])

通過在兩邊填充字符(默認(rèn)為空格)讓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*****'

詳細(xì)的String參數(shù)可參考官網(wǎng)文檔:

https://docs.python.org/3.7/library/stdtypes.html?highlight=replace#str.replace

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI