如何切换字符串中2个字符的位置?

问题描述 投票:0回答:2

我想在Python中切换位置后的空格和字符。输入示例:

"Hell oWorld"

预期产出:

"Hello World"

我尝试运行以下代码:

text = "Hell oWorld"
text = list(text)
for x in range(len(text)):
    if text[x] == " ":
        text[x], text[x + 1] = text[x + 1], text[x]
text = "".join(text)

但结果是

IndexError: list index out of range
.

非常感谢任何帮助。

python python-3.x string
2个回答
1
投票

看起来你在评论中得到了合理的建议,一个替代解决方案,使用带有捕获组的

.sub
方法的正则表达式可能更容易。

import re 
s = 'Hell oWorld'

subbed = re.sub('(\s)(\w)', r'\2\1',s)

print(subbed)

'Hello World'

0
投票

你可以尝试这样的事情:

s = "Hell oWorld"
result, *rest = s.split()

for word in rest:
    result += f"{word[0]} {word[1:]}"

结果:

Hello World
© www.soinside.com 2019 - 2024. All rights reserved.