Python字符串可以通过索引的方式来赋值修改吗

Python字符串可以索引赋值吗

Python的字符串是不可修改的,即便是通过python字符串的一系列的方法,比如replace()、title()等也是返回新的字符串,并不对原字符串进行修改,如果尝试通过字符串索引并赋值的方式来修改字符串,python会抛出TypeError: 'str' object does not support item assignment。比如下方的这个实例:

>>> string = "笨鸟工具,x1y1z1.com"
>>> string[0] = '聪明'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Python字符串如何修改

如果要修改python字符串中的某一个字符,并修改存储原字符串的变量,可以对该变量进行重新的赋值。下方的实例中通过replace()方法来修改原字符串中的某个字符并重新赋值,实例代码如下:

>>> string2 = "abc"
>>> string2 = string2.replace("a","d")
>>> string2
'dbc'

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.