用 Python 交换字符串中每对相邻字符的最简单方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4605439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the simplest way to swap each pair of adjoining chars in a string with Python?
提问by cocobear
I want to swap each pair of characters in a string. '2143'becomes '1234', 'badcfe'becomes 'abcdef'.
我想交换字符串中的每一对字符。'2143'变成'1234','badcfe'变成'abcdef'。
How can I do this in Python?
我怎样才能在 Python 中做到这一点?
采纳答案by Paulo Scardine
oneliner:
单线:
>>> s = 'badcfe'
>>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])
'abcdef'
- s[x:x+2] returns string slice from x to x+2; it is safe for odd len(s).
- [::-1] reverses the string in Python
- range(0, len(s), 2) returns 0, 2, 4, 6 ... while x < len(s)
- s[x:x+2] 返回从 x 到 x+2 的字符串切片;对于奇数 len(s) 来说是安全的。
- [::-1] 在 Python 中反转字符串
- range(0, len(s), 2) 返回 0, 2, 4, 6 ... 而 x < len(s)
回答by FogleBird
Here's one way...
这是一种方法...
>>> s = '2134'
>>> def swap(c, i, j):
... c = list(c)
... c[i], c[j] = c[j], c[i]
... return ''.join(c)
...
>>> swap(s, 0, 1)
'1234'
>>>
回答by Spacedman
Do you want the digits sorted? Or are you swapping odd/even indexed digits? Your example is totally unclear.
你想对数字进行排序吗?或者你在交换奇数/偶数索引数字?你的例子完全不清楚。
Sort:
种类:
s = '2143'
p=list(s)
p.sort()
s = "".join(p)
s is now '1234'. The trick is here that list(string) breaks it into characters.
s 现在是“1234”。诀窍在于 list(string) 将其分解为字符。
回答by Spacedman
Loop over length of string by twos and swap:
循环遍历字符串的长度并交换:
def oddswap(st):
s = list(st)
for c in range(0,len(s),2):
t=s[c]
s[c]=s[c+1]
s[c+1]=t
return "".join(s)
giving:
给予:
>>> s
'foobar'
>>> oddswap(s)
'ofbora'
and fails on odd-length strings with an IndexError exception.
并在奇数长度的字符串上失败并出现 IndexError 异常。
回答by Duncan
The usual way to swap two items in Python is:
在 Python 中交换两个项目的常用方法是:
a, b = b, a
So it would seem to me that you would just do the same with an extended slice. However, it is slightly complicated because strings aren't mutable; so you have to convert to a list and then back to a string.
Therefore, I would do the following:
因此,在我看来,您只需对扩展切片执行相同操作即可。然而,它有点复杂,因为字符串是不可变的;所以你必须转换成一个列表,然后再转换回一个字符串。
因此,我会执行以下操作:
>>> s = 'badcfe'
>>> t = list(s)
>>> t[::2], t[1::2] = t[1::2], t[::2]
>>> ''.join(t)
'abcdef'
回答by Cristian Ciupitu
''.join(s[i+1]+s[i] for i in range(0, len(s), 2)) # 10.6 usec per loop
or
或者
''.join(x+y for x, y in zip(s[1::2], s[::2])) # 10.3 usec per loop
or if the string can have an odd length:
或者如果字符串可以有一个奇数长度:
''.join(x+y for x, y in itertools.izip_longest(s[1::2], s[::2], fillvalue=''))
Note that this won't work with old versions of Python (if I'm not mistaking older than 2.5).
请注意,这不适用于旧版本的 Python(如果我没有误认为是 2.5 以上)。
The benchmark was run on python-2.7-8.fc14.1.x86_64 and a Core 2 Duo 6400 CPU with s='0123456789'*4.
基准测试在 python-2.7-8.fc14.1.x86_64 和 Core 2 Duo 6400 CPU 上运行,s='0123456789'*4.
回答by Lennart Regebro
Like so:
像这样:
>>> s = "2143658709"
>>> ''.join([s[i+1] + s[i] for i in range(0, len(s), 2)])
'1234567890'
>>> s = "badcfe"
>>> ''.join([s[i+1] + s[i] for i in range(0, len(s), 2)])
'abcdef'
回答by Kabie
re.sub(r'(.)(.)',r"",'abcdef1234')
However re is a bit slow.
不过re有点慢。
def swap(s):
i=iter(s)
while True:
a,b=next(i),next(i)
yield b
yield a
''.join(swap("abcdef1234"))
回答by john doe
If performance or elegance is not an issue, and you just want clarity and have the job done then simply use this:
如果性能或优雅不是问题,而您只是想要清晰并完成工作,那么只需使用以下命令:
def swap(text, ch1, ch2):
text = text.replace(ch2, '!',)
text = text.replace(ch1, ch2)
text = text.replace('!', ch1)
return text
This allows you to swap or simply replace chars or substring. For example, to swap 'ab' <-> 'de' in a text:
这允许您交换或简单地替换字符或子字符串。例如,要在文本中交换 'ab' <-> 'de':
_str = "abcdefabcdefabcdef"
print swap(_str, 'ab','de') #decabfdecabfdecabf
回答by cayhorstmann
There is no need to make a list. The following works for even-length strings:
没有必要列出清单。以下适用于偶数长度的字符串:
r = ''
for in in range(0, len(s), 2) :
r += s[i + 1] + s[i]
s = r

