gpt4 book ai didi

python - 互相替换字符串内容

转载 作者:行者123 更新时间:2023-12-03 09:26:52 24 4
gpt4 key购买 nike

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

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

输出为 1x11x1x

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

最佳答案

这是使用字符串的 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 方法用于将字符与其他字符交换。如果您想交换子字符串,您应该使用 replace 方法,如 Rohit Jain 演示的那样。

关于python - 互相替换字符串内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19012198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com