2013-09-25 61 views
0

我有一个字符串:1x22x1x。 我需要全部替换1到2,反之亦然。因此示例行将是2x11x2x。只是想知道它是如何完成的。我试图用互相替换字符串内容

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

输出1x11x1x

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

回答

1

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

b = a.replace('1', '@[email protected]').replace('2', '1').replace('@[email protected]', '2') 

但这可能会失败,如果你的字符串已经包含@[email protected]。该技术在PEP 378

+0

是的,它几乎没有问题。输出给了我'@ temp_replacex11x @ temp_replacex'。所以还有一些事情需要完成。 – Waldema

+0

@Waldema。你确定你有这个输出吗?我得到[正确的输出](http://ideone.com/IaGY13) –

+0

正面,双重检查..:o或者我只是打字? – Waldema

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方法。

+0

如果我们想用'abc'替换'abc'与'xyz'和'xyz'以'abc',这个工作吗? –

+0

这一些如何返回一个错误:TypeError:预期一个字符缓冲区对象 – Waldema

+0

@Waldema - 抱歉关于延迟 - 我无法重新创建您的错误。最终,我意识到你必须使用Python 2.x,因为只能这样做。我编辑了我的帖子以支持2.x. – iCodez

0

如果“来源”都是一个字符,你可以做一个新的字符串:

>>> 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字典中,则使用相关的值,否则您只需使用该字符本身。

相关问题