我想反转字符串
输入:
I love my country! It is @beautiful
输出:
I evol ym yrtnuoc! tI si @lufituaeb
从每个单词中,使用正则表达式,提取出没有标点符号的部分,将其反转并替换
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
单行:
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'