python修改字符串的值

由于元组和字符串中的值不允许被修改,所以在这里介绍三种方法:

1.使用字符串的replace函数

oldstr = 'abcda'
newstr = oldstr.replace('a', 'e')
print(oldstr, newstr, sep='\n')

输出结果为:abcda, ebcde
将a替换为e

2.将字符串转换成列表后修改值,然后用join组成新字符串

oldstr = 'abcda'
newstr = list(oldstr)
newstr[4] = 'e'
print(string, ''.join(newstr), sep='\n')

输出结果为:abcda, ebcde
将a替换为e

3.使用序列切片方式

oldstr = 'abcda'
newstr = oldstr[:4] + 'e' + oldstr[5:]
print(oldstr, newstr, sep='\n')

输出结果为:abcda, ebcde
将a替换为e

大概就是这三种,有其他的欢迎补充!

猜你喜欢

转载自blog.csdn.net/qq_41542989/article/details/108974157