问题描述:将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I
代码:
def rev1(s):
return ' '.join(reversed(s.split()))
def rev2(s):
t = s.split()
t.reverse()
return ' '.join(t)
def rev3(s):
'''考虑开头或结束有空格的情况'''
import re
t = re.split('\s+', s.strip())
t.reverse()
return ' '.join(t)
def rev4(s):
'''考虑开头或结束有空格的情况'''
import re
t = re.split('\s+', s.strip())
return ' '.join(reversed(t))
def rev5(s):
'''字符串整体逆序,分隔,再各单词逆序'''
t = ''.join(reversed(s)).split()
t = map(lambda x:''.join(reversed(x)), t)
return ' '.join(t)
#测试
import string
import random
source = string.ascii_letters + ' ,.?'
for i in range(100000):
s = ''.join((random.choice(source) for _ in range(100)))
s1, s2, s3, s4,s5 = rev1(s), rev2(s), rev3(s), rev4(s), rev5(s)
if not (s1==s2==s3==s4==s5):
print('='*30)
print('{0}\n{1}\n{2}\n{3}\n{4}\n{5}'.format(s,s1,s2,s3,s4,s5))
运行结果:
无输出,说明几种方法处理结果一致。