我想在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
.看起来你在评论中得到了合理的建议,一个替代解决方案,使用带有捕获组的
.sub
方法的正则表达式可能更容易。
import re
s = 'Hell oWorld'
subbed = re.sub('(\s)(\w)', r'\2\1',s)
print(subbed)
'Hello World'
你可以尝试这样的事情:
s = "Hell oWorld"
result, *rest = s.split()
for word in rest:
result += f"{word[0]} {word[1:]}"
结果:
Hello World