是否可以替换字符串中多次出现的单个字符?在
输入:
Sentence=("This is an Example. Thxs code is not what I'm having problems with.") #Example input
^
Sentence=("This is an Example. This code is not what I'm having problems with.") #Desired output
将"Thxs"
中的“x”替换为i
,而不替换"Example"
中的x
。在
Tags:
您可以通过包含一些上下文来实现:
或者,您可以保留一个您不想替换的单词列表:
^{2}$输出:
当然,但是你必须从你想要的部分中建立一个新的字符串:
有关这里使用的符号的信息,请参见good primer for python slice notation。在
如果您知道要替换第一个出现的},如果您希望从字符串的末尾开始)与切片和
x
,或者第二个,或者第三个,或者最后一个,那么您可以将str.find
(或者{str.replace
结合使用,将要替换的字符输入到第一个方法中,以获得位置所需的次数为准在要替换的字符之前(对于您建议的特定句子,只替换一个),然后将字符串分成两部分,在第二个片段中只替换一个出现的字符。在一个例子胜过千言万语,或者他们说的那样。在下面,我假设您想要替换这个字符的第(
n
+1)次出现。在请注意,您需要向
pos
添加偏移量,否则将替换刚刚找到的x
的出现。在相关问题 更多 >
编程相关推荐