python 替换python中字符串的一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2165172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing one character of a string in python
提问by Chris
In python, are strings mutable? The line someString[3] = "a"
throws the error
在python中,字符串是可变的吗?该行someString[3] = "a"
抛出错误
TypeError: 'str' object does not support item assignment
类型错误:“str”对象不支持项目分配
I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method to do this in python?
我明白为什么(因为我可以写 someString[3] = "test" 并且这显然是非法的)但是有没有一种方法可以在 python 中做到这一点?
回答by H?vard S
Python strings are immutable, which means that they do not support item or slice assignment. You'll have to build a new string using i.e. someString[:3] + 'a' + someString[4:]
or some other suitable approach.
Python 字符串是不可变的,这意味着它们不支持项目或切片分配。您必须使用 iesomeString[:3] + 'a' + someString[4:]
或其他一些合适的方法构建一个新字符串。
回答by Mark Byers
Instead of storing your value as a string, you could use a list of characters:
您可以使用字符列表,而不是将您的值存储为字符串:
>>> l = list('foobar')
>>> l[3] = 'f'
>>> l[5] = 'n'
Then if you want to convert it back to a string to display it, use this:
然后,如果要将其转换回字符串以显示它,请使用以下命令:
>>> ''.join(l)
'foofan'
If you are changing a lot of characters one at a time, this method will be considerably faster than building a new string each time you change a character.
如果您一次更改多个字符,则此方法将比每次更改一个字符时构建一个新字符串快得多。
回答by mzz
In new enough pythons you can also use the builtin bytearray
type, which is mutable. See the stdlib documentation. But "new enough" here means 2.6 or up, so that's not necessarily an option.
在足够新的 python 中,您还可以使用内置bytearray
类型,它是可变的。请参阅标准库文档。但是这里的“足够新”意味着 2.6 或更高版本,因此这不一定是一个选项。
In older pythons you have to create a fresh str
as mentioned above, since those are immutable. That's usually the most readable approach, but sometimes using a different kind of mutable sequence (like a list of characters, or possibly an array.array
) makes sense. array.array
is a bit clunky though, and usually avoided.
在较旧的 python 中,您必须str
如上所述创建一个新的,因为它们是不可变的。这通常是最易读的方法,但有时使用不同类型的可变序列(如字符列表,或者可能是array.array
)是有意义的。array.array
虽然有点笨重,但通常会避免。
回答by JohnMudd
>>> import ctypes
>>> s = "1234567890"
>>> mutable = ctypes.create_string_buffer(s)
>>> mutable[3] = "a"
>>> print mutable.value
123a567890
回答by Hekmatullah Rahmany
just define a new string equaling to what you want to do with your current string.
只需定义一个新字符串,该字符串等于您要对当前字符串执行的操作。
a= str.replace(str[n],"") return a
a= str.replace(str[n],"") 返回一个