如何在保留标点符号位置的情况下反转字符串? [重复]

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

我想反转字符串

输入:

I love my country! It is @beautiful

输出:

I evol ym yrtnuoc! tI si @lufituaeb
python python-3.x
2个回答
2
投票

从每个单词中,使用正则表达式,提取出没有标点符号的部分,将其反转并替换

import re

inp = 'I love my country! It is @beautiful'
out = []

for w in inp.split(' '):
    sw = re.search(r'[a-zA-Z]+', w)[0]
    out.append(w.replace(sw, sw[::-1]))
print(' '.join(out))

打印:

I evol ym yrtnuoc! tI si @lufituaeb

2
投票

单行:

import re
text = 'I love my country! It is @beautiful'
''.join([ s[::-1] for s in re.split(r'(\W)', text)])

结果:

'I evol ym yrtnuoc! tI si @lufituaeb'
© www.soinside.com 2019 - 2024. All rights reserved.