python中字串無法改變的解決辦法

2021-10-03 20:14:49 字數 1469 閱讀 7531

報錯:

typeerror: 『str』 object does not support item assignment

在python中,字串是不可變型別,即無法直接修改字串的某一位字元。

因此改變乙個字串的元素需要新建乙個新的字串。

常見的修改方法有以下4種

方法1:將字串轉換成列表後修改值,然後用join組成新字串

>>> s='abcdef'         #原字串

>>> s1=list(s) #將字串轉換為列表

>>> s1

['a', 'b', 'c', 'd', 'e', 'f'] #列表的每乙個元素為乙個字元

>>> s1[4]='e' #將列表中的第5個字元修改為e

>>> s1[5]='f' #將列表中的第5個字元修改為e

>>> s1

['a', 'b', 'c', 'd', 'e', 'f']

>>> s=''.join(s1) #用空串將列表中的所有字元重新連線為字串

>>> s

'abcdef' #新字串

方法2: 通過字串序列切片方式

>>> s='hello world' 

>>> s=s[:6] + 'bital' #s前6個字串+'bital'

>>> s

'hello bital'

>>> s=s[:3] + s[8:] #s前3個字串+s第8位之後的字串

>>> s

'heltal'

方法3: 使用字串的replace函式

>>> s='abcdef'

>>> s=s.replace('a','a') #用a替換a

>>> s

'abcdef'

>>> s=s.replace('bcd','123') #用123替換bcd

>>> s

'a123ef'

方法4: 通過給乙個變數賦值(或者重新賦值)

>>> s='hello world'

>>> s2=' 2017' #變數賦值

>>> s=s+s2

>>> s

'hello world 2017'

>>> s='hello world'

>>> s='hello world 2017' #重新賦值

>>> s

'hello world 2017'

replace java 無法改變原字串

內部使用,刪除部分字串 例如 從 1,2,3,4,5,6 中刪除 2,3,5 等 param prestr 初始字串,結尾沒有分號,param substr 需要刪除的字串 return 處理後的字串,結尾沒有分號,private string delsubstring string prestr,...

python中的字串

方法1 用字串的join方法 a a b c d content content join a print content 方法2 用字串的替換佔位符替換 a a b c d content content s s s s tuple a print content 我們可以通過索引來提取想要獲取的...

python中的字串

b nihao hahah xixi 輸出 nihao nhahah nxixi n 原字串 big r this hhaha big輸出 this nhhaha 還原為unicode字串 hello u hello u0020world hello輸出 hello world 字串是不可以改變的 ...