Python中的“就地”字符串修改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3463746/
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
'in-place' string modifications in Python
提问by Paul Nathan
In Python, strings are immutable.
在 Python 中,字符串是不可变的。
What is the standard idiom to walk through a string character-by-character and modify it?
逐个字符遍历字符串并对其进行修改的标准习语是什么?
The only methods I can think of are some genuinely stanky hacks related to joining against a result string.
我能想到的唯一方法是一些与连接结果字符串相关的真正糟糕的黑客攻击。
--
——
In C:
在 C 中:
for(int i = 0; i < strlen(s); i++)
{
s[i] = F(s[i]);
}
This is superexpressive and says exactly what I am doing. That is what I am looking for.
这是超级的表现,说我在做什么。这就是我正在寻找的。
回答by jathanism
Strings are iterable and can be walked through like lists. Strings also have a number of basic methods such as .replace()that might be what you're looking for. All string methods return a new string. So instead of modifying the string in place you can simply replace its existing value.
字符串是可迭代的,可以像列表一样遍历。字符串也有许多基本方法,例如.replace()您可能正在寻找的方法。所有字符串方法都返回一个新字符串。因此,您可以简单地替换其现有值,而不是修改字符串。
>>> mystring = 'robot drama'
>>> mystring = mystring.replace('r', 'g')
>>> mystring
'gobot dgama'
回答by Jungle Hunter
>>> mystring = "Th1s 1s my str1ng"
>>> mystring.replace("1", "i")
'This is my string'
If you want to store this newstring you'll have to mystring = mystring.replace("1", "i"). This is because in Python strings are immutable.
如果你想存储这个新字符串,你必须mystring = mystring.replace("1", "i"). 这是因为在 Python 中字符串是不可变的。
回答by Tim McNamara
string.translateis probably the closest function to what you're after.
string.translate可能是最接近您所追求的功能。
回答by bstpierre
Don't use a string, use something mutable like bytearray:
不要使用字符串,使用像字节数组这样的可变内容:
#!/usr/bin/python
s = bytearray("my dog has fleas")
for n in xrange(len(s)):
s[n] = chr(s[n]).upper()
print s
Results in:
结果是:
MY DOG HAS FLEAS
Edit:
编辑:
Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:
由于这是一个bytearray,因此您(不一定)不会使用characters。您正在使用bytes。所以这也有效:
s = bytearray("\x81\x82\x83")
for n in xrange(len(s)):
s[n] = s[n] + 1
print repr(s)
gives:
给出:
bytearray(b'\x82\x83\x84')
If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.
如果您想修改 Unicode 字符串中的字符,您可能想要使用memoryview,尽管它不直接支持 Unicode。
回答by Joe Koberg
def modifyIdx(s, idx, newchar):
return s[:idx] + newchar + s[idx+1:]
回答by David Z
Assigning a particular character to a particular index in a string is not a particularly common operation, so if you find yourself needing to do it, think about whether there may be a better way to accomplish the task. But if you do need to, probably the most standard way would be to convert the string to a list, make your modifications, and then convert it back to a string.
将特定字符分配给字符串中的特定索引并不是特别常见的操作,因此如果您发现自己需要这样做,请考虑是否有更好的方法来完成任务。但是,如果确实需要,最标准的方法可能是将字符串转换为列表,进行修改,然后再将其转换回字符串。
s = 'abcdefgh'
l = list(s)
l[3] = 'r'
s2 = ''.join(l)
EDIT:As posted in bstpierre's answer, bytearrayis probably even better for this task than list, as long as you're not working with Unicode strings.
编辑:正如 bstpierre's answer 中发布的那样,只要您不使用 Unicode 字符串bytearray,这项任务可能比 更好list。
s = 'abcdefgh'
b = bytearray(s)
b[3] = 'r'
s2 = str(b)
回答by Zimm3r
If I ever need to do something like that I just convert it to a mutable list
如果我需要做类似的事情,我只需将其转换为可变列表
For example... (though it would be easier to use sort (see second example) )
例如......(虽然使用排序会更容易(见第二个例子))
>>> s = "abcdfe"
>>> s = list(s)
>>> s[4] = "e"
>>> s[5] = "f"
>>> s = ''.join(s)
>>> print s
abcdef
>>>
# second example
>>> s.sort()
>>> s = ''.join(s)
回答by Odomontois
回答by killown
you can use the UserString module:
您可以使用 UserString 模块:
>>> import UserString
... s = UserString.MutableString('Python')
... print s
Python
>>> s[0] = 'c'
>>> print s
cython
回答by John La Rooy
Here is an example using translate to switch "-" with "." and uppercase "a"s
这是一个使用 translate 将“-”切换为“.”的示例。和大写的“a”
>>> from string import maketrans
>>> trans_table = maketrans(".-a","-.A")
>>> "foo-bar.".translate(trans_table)
'foo.bAr-'
This is much more efficient that flipping to byte array and back if you just need to do single char replacements
如果您只需要进行单个字符替换,这比翻转到字节数组并返回效率要高得多

