在Python中替换字符串中的字符最简单的方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
在Python中替换字符串中的字符最简单的方法是什么?
例如:
text = "abcdefg";
text[1] = "Z";
^
当前回答
试试这个:
old_string = "mba"
string_list = list(old_string)
string_list[2] = "e"
//Replace 3rd element
new_string = "".join(string_list)
print(new_string)
其他回答
从python 2.6和python 3开始,你可以使用可变的bytearrays(可以像字符串那样按元素改变):
s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg
编辑:将str改为s
edit2:正如Two-Bit Alchemist在评论中提到的,这段代码不能使用unicode。
在单行if语句中结合find和replace方法的解决方案可以是:
```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}") # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}") # my_new_var = stackoverflow
```
Python字符串是不可变的,你可以通过复制来改变它们。 做你想做的事情最简单的方法可能是:
text = "Z" + text[1:]
文本[1:]返回文本中从位置1到末尾的字符串,位置从0开始计数,因此'1'是第二个字符。
编辑: 您可以对字符串的任何部分使用相同的字符串切片技术
text = text[:1] + "Z" + text[2:]
或者如果字母只出现一次,你可以使用搜索和替换技巧 下面
new = text[:1] + 'Z' + text[2:]
不要修改字符串。
将它们作为列表来处理;只在需要时将它们转换为字符串。
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
Python字符串是不可变的(即它们不能被修改)。这有很多原因。使用列表,直到你别无选择,然后才把它们变成字符串。