我有一个字符串:1x22x1x。 我需要全部替换1到2,反之亦然。因此示例行将是2x11x2x。只是想知道它是如何完成的。我试图用互相替换字符串内容
a = "1x22x1x"
b = a.replace('1', '2').replace('2', '1')
print b
输出1x11x1x
也许我应该忘记使用替代..?
我有一个字符串:1x22x1x。 我需要全部替换1到2,反之亦然。因此示例行将是2x11x2x。只是想知道它是如何完成的。我试图用互相替换字符串内容
a = "1x22x1x"
b = a.replace('1', '2').replace('2', '1')
print b
输出1x11x1x
也许我应该忘记使用替代..?
一种方法是使用一些临时性的字符串作为中间替换:
b = a.replace('1', '@[email protected]').replace('2', '1').replace('@[email protected]', '2')
但这可能会失败,如果你的字符串已经包含@[email protected]
。该技术在PEP 378
也说明这是一个使用字符串的方法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
方法。
如果“来源”都是一个字符,你可以做一个新的字符串:
>>> a = "1x22x1x"
>>> replacements = {"1": "2", "2": "1"}
>>> ''.join(replacements.get(c,c) for c in a)
'2x11x2x'
督察,用get
方法,接受默认的参数做出一个新的字符串。 somedict.get(c,c)
表示类似于somedict[c] if c in somedict else c
,因此如果该字符位于replacements
字典中,则使用相关的值,否则您只需使用该字符本身。
是的,它几乎没有问题。输出给了我'@ temp_replacex11x @ temp_replacex'。所以还有一些事情需要完成。 – Waldema
@Waldema。你确定你有这个输出吗?我得到[正确的输出](http://ideone.com/IaGY13) –
正面,双重检查..:o或者我只是打字? – Waldema