将字符串内容替换为彼此

时间:2013-09-25 18:12:09

标签: python replace

我有一个字符串:1x22x1x。 我需要替换所有1到2,反之亦然。所以示例行为2x11x2x。只是想知道它是如何完成的。我试过了

a = "1x22x1x"
b = a.replace('1', '2').replace('2', '1')
print b

输出为1x11x1x

也许我应该忘记使用替换..?

3 个答案:

答案 0 :(得分:4)

以下是使用字符串的translate方法的方法:

>>> a = "1x22x1x"
>>> a.translate({ord('1'):'2', ord('2'):'1'})
'2x11x2x'
>>>
>>> # Just to explain
>>> help(str.translate)
Help on method_descriptor:

translate(...)
    S.translate(table) -> str

    Return a copy of the string S, where all characters have been mapped
    through the given translation table, which must be a mapping of
    Unicode ordinals to Unicode ordinals, strings, or None.
    Unmapped characters are left untouched. Characters mapped to None
    are deleted.

>>>

但请注意,我是为Python 3.x编写的。在2.x中,您需要这样做:

>>> from string import maketrans
>>> a = "1x22x1x"
>>> a.translate(maketrans('12', '21'))
'2x11x2x'
>>>

最后,重要的是要记住translate方法用于与其他字符交换字符。如果要交换子串,则应使用Rohit Jain演示的replace方法。

答案 1 :(得分:1)

一种方法是使用一些临时字符串作为中间替换:

b = a.replace('1', '@temp_replace@').replace('2', '1').replace('@temp_replace@', '2')

但如果您的字符串已包含@temp_replace@,则可能会失败。 PEP 378

中也描述了这种技术

答案 2 :(得分:0)

如果“sources”都是一个字符,您可以创建一个新字符串:

>>> a = "1x22x1x"
>>> replacements = {"1": "2", "2": "1"}
>>> ''.join(replacements.get(c,c) for c in a)
'2x11x2x'

IOW,使用接受默认参数的get方法创建一个新字符串。 somedict.get(c,c)表示类似somedict[c] if c in somedict else c的内容,因此如果字符位于replacements字典中,则使用关联值,否则您只需使用字符本身。