def reverse_string_by_word(s): lst = s.split() # split by blank space by default return ' '.join(lst[::-1]) s = 'Power of Love' print reverse_string_by_word(s) # Love of Power s = 'Hello World!' print reverse_string_by_word(s) # World! Hello
print reverse_string_by_word(s) # Expected: !World Hello
>>> import re >>> s = 'Hello World!' >>> re.split(r'\s+', s) # will discard blank spaces ['Hello', 'World!'] >>> re.split(r'(\s+)', s) # will keep spaces as a group ['Hello', ' ', 'World!'] >>> s = '< Welcome to EF.COM! >' >>> re.split(r'\s+', s) # split by spaces ['<', 'Welcome', 'to', 'EF.COM!', '>'] >>> re.split(r'(\w+)', s) # exactly split by word ['< ', 'Welcome', ' ', 'to', ' ', 'EF', '.', 'COM', '! >'] >>> re.split(r'(\s+|\w+)', s) # split by space and word ['<', ' ', '', 'Welcome', '', ' ', '', 'to', '', ' ', '', 'EF', '.', 'COM', '!', ' ', '>'] >>> ''.join(re.split(r'(\s+|\w+)', s)[::-1]) '> !COM.EF to Welcome <' >>> ''.join(re.split(r'(\s+)', s)[::-1]) '> EF.COM! to Welcome <' >>> ''.join(re.split(r'(\w+)', s)[::-1]) '! >COM.EF to Welcome< '
>>> ''.join(reversed(re.split(r'(\s+|\w+)', s))) '> !COM.EF to Welcome <'
# -*- coding: utf-8 -*- #eclipse pydev, python 3.3 #by C.L.Wang #time: 2014. 4. 11 string = 'abcdef' def string_reverse1(string): return string[::-1] def string_reverse2(string): t = list(string) l = len(t) for i,j in zip(range(l-1, 0, -1), range(l//2)): t[i], t[j] = t[j], t[i] return "".join(t) def string_reverse3(string): if len(string) <= 1: return string return string_reverse3(string[1:]) + string[0] from collections import deque def string_reverse4(string): d = deque() d.extendleft(string) return ''.join(d) def string_reverse5(string): #return ''.join(string[len(string) - i] for i in range(1, len(string)+1)) return ''.join(string[i] for i in range(len(string)-1, -1, -1)) print(string_reverse1(string)) print(string_reverse2(string)) print(string_reverse3(string)) print(string_reverse4(string)) print(string_reverse5(string))
fedcba fedcba fedcba fedcba fedcba
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有