Python中如何修改字符串的值
生活随笔
收集整理的這篇文章主要介紹了
Python中如何修改字符串的值
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Python中列表list中的值是可修改的,而元組和字符串的值是不可修改的。看下面的示例:string = 'abcdafg'
string[4] = 'e'
print(string)輸出結(jié)果:string[4]?=?'e'TypeError:?'str'?object?does?not?support?item?assignment
但在實際應(yīng)用中,經(jīng)常需要對字符串的值進(jìn)行一些修改操作,解決方案有3種:(1)使用字符串的replace函數(shù)string = 'abcdafg'
newstr = string.replace('a', 'e')
print(string, newstr, sep='\n')輸出結(jié)果:abcdafgebcdefg可以看出,replace會生成一個新的字符串,原字符串仍然不變。replace會修改字符串中所有相關(guān)的子串。很多時候并不能滿足我們的應(yīng)用要求。(2)將字符串轉(zhuǎn)換成列表后修改值,然后用join組成新字符串string = 'abcdafg'
newstr = list(string)
newstr[4] = 'e'
print(string, ''.join(newstr), sep='\n')輸出結(jié)果:abcdafgabcdefg(3)使用序列切片方式字符串本身也是一種序列,可以使用序列切片的方式。http://saltriver.blog.163.com/blog/static/2260971542016525103755389/string = 'abcdafg'
newstr = string[:4] + 'e' + string[5:]
print(string, newstr, sep='\n')輸出結(jié)果:abcdafgabcdefg
string[4] = 'e'
print(string)輸出結(jié)果:string[4]?=?'e'TypeError:?'str'?object?does?not?support?item?assignment
但在實際應(yīng)用中,經(jīng)常需要對字符串的值進(jìn)行一些修改操作,解決方案有3種:(1)使用字符串的replace函數(shù)string = 'abcdafg'
newstr = string.replace('a', 'e')
print(string, newstr, sep='\n')輸出結(jié)果:abcdafgebcdefg可以看出,replace會生成一個新的字符串,原字符串仍然不變。replace會修改字符串中所有相關(guān)的子串。很多時候并不能滿足我們的應(yīng)用要求。(2)將字符串轉(zhuǎn)換成列表后修改值,然后用join組成新字符串string = 'abcdafg'
newstr = list(string)
newstr[4] = 'e'
print(string, ''.join(newstr), sep='\n')輸出結(jié)果:abcdafgabcdefg(3)使用序列切片方式字符串本身也是一種序列,可以使用序列切片的方式。http://saltriver.blog.163.com/blog/static/2260971542016525103755389/string = 'abcdafg'
newstr = string[:4] + 'e' + string[5:]
print(string, newstr, sep='\n')輸出結(jié)果:abcdafgabcdefg
總結(jié)
以上是生活随笔為你收集整理的Python中如何修改字符串的值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python的操作符重载
- 下一篇: Python的集合set