如何在python中替换部分字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3550327/
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
how to substitute part of a string in python?
提问by user63503
How to replace a set of characters inside another string in Python?
如何替换 Python 中另一个字符串中的一组字符?
Here is what I'm trying to do: let's say I have a string 'abcdefghijkl' and want to replace the 2-d from the end symbol (k) with A. I'm getting an error:
这是我想要做的:假设我有一个字符串 'abcdefghijkl' 并且想用 A 替换结尾符号 (k) 中的 2-d。我收到一个错误:
>>> aa = 'abcdefghijkl'
>>> print aa[-2]
k
>>> aa[-2]='A'
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
aa[-2]='A'
TypeError: 'str' object does not support item assignment
So, the question: is there an elegant way to replace (substitute) with a string symbols inside another string starting from specified position? Something like:
那么,问题是:是否有一种优雅的方法可以从指定位置开始用另一个字符串中的字符串符号替换(替换)?就像是:
# subst(whole_string,symbols_to_substiture_with,starting_position)
>>> print aa
abcdefghijkl
>>> aa = subst(aa,'A',-2)
>>> print aa
abcdefghijAl
What would be a not-brute-force code for the subst?
subst 的非蛮力代码是什么?
采纳答案by eldarerathis
If it's always the same position you're replacing, you could do something like:
如果它总是与您要替换的位置相同,则可以执行以下操作:
>>> s = s[0:-2] + "A" + s[-1:]
>>> print s
abcdefghijAl
In the general case, you could do:
在一般情况下,你可以这样做:
>>> rindex = -2 #Second to the last letter
>>> s = s[0:rindex] + "A" + s[rindex+1:]
>>> print s
abcdefghijAl
Edit: The verygeneral case, if you just want to repeat a single letter in the replacement:
编辑:非常普遍的情况,如果您只想在替换中重复单个字母:
>>> s = "abcdefghijkl"
>>> repl_str = "A"
>>> rindex = -4 #Start at 4th character from the end
>>> repl = 3 #Replace 3 characters
>>> s = s[0:rindex] + (repl_str * repl) + s[rindex+repl:]
>>> print s
abcdefghAAAl
回答by Manoj Govindan
TypeError: 'str' object does not support item assignment
This is to be expected - python strings are immutable.
这是意料之中的——python 字符串是不可变的。
One way is to do some slicing and dicing. Like this:
一种方法是进行一些切片和切块。像这样:
>>> aa = 'abcdefghijkl'
>>> changed = aa[0:-2] + 'A' + aa[-1]
>>> print changed
abcdefghijAl
The result of the concatenation, changedwill be another immutable string. Mind you, this is not a generic solution that fits all substitution scenarios.
连接的结果changed将是另一个不可变的字符串。请注意,这不是适合所有替代方案的通用解决方案。
回答by Eric Mickelsen
You have to slice it up and instantiate a new string since strings are immutable:
您必须将其切片并实例化一个新字符串,因为字符串是不可变的:
aa = aa[:-2] + 'A' + aa[-1:]
回答by cji
Another way to do this:
另一种方法来做到这一点:
s = "abcdefghijkl"
l = list( s )
l[-2] = 'A'
s = "".join( l )
Strings in Python are immutable sequences - very much like tuples. You can make a list, which is mutable, from string or tuple, change relevant indexes and transform the list back into string with joinor into tuplewith tuple constructor.
Python 中的字符串是不可变的序列——非常像元组。您可以从字符串或元组创建一个可变的列表,更改相关索引并使用元组构造函数将列表转换回字符串join或将tuple其转换回字符串。
EDIT:in case of strings you can use bytearray (docs) type instead of list, which makes transforming into string possible with strconstructor.
编辑:在字符串的情况下,您可以使用 bytearray ( docs) 类型而不是list,这使得可以使用str构造函数转换为字符串。
Also, you could implement your own or use this class from standard library: http://docs.python.org/library/userdict.html#UserString.MutableStringlike so:
此外,您可以实现自己的或使用标准库中的此类:http: //docs.python.org/library/userdict.html#UserString.MutableString,如下所示:
>>> from UserString import MutableString
>>> s = MutableString( "zdfgzbdr " )
>>> s
'zdfgzbdr '
>>> s[1:5]
'dfgz'
>>> s[1:5] = "xxxx"
>>> s
'zxxxxbdr '
Sadly - MutableStringis deprecated and not available in Py3k (you can still write your own class, I think).
可悲的是 -MutableString已弃用且在 Py3k 中不可用(我认为您仍然可以编写自己的类)。
回答by Tony Veijalainen
To reply comment of other post:
回复其他帖子的评论:
To make three character substitution directly with strings (see also the bytearray post) you can do partition with the sequence, especially if you do not know the position without search:
要直接用字符串进行三个字符替换(另请参见 bytearray 帖子),您可以对序列进行分区,特别是如果您不知道位置而不搜索时:
aa = 'abcdefghijkl'
replace = 'def'
withstring = 'QRS'
newstr,found,endpart = aa.partition(replace)
if found:
newstr+=withstring+endpart
print newstr
else:
print "%r string is not in %r" % (replace,aa)
The length of replacement does not need to match the original in this case.
在这种情况下,替换的长度不需要与原始匹配。

