來源:公眾號-哎媽呀Bug 鏈接: https://mp.weixin.qq.com/s/wC5x8fRAwVvZYs3YGVr5iw
按單詞反轉(zhuǎn)字符串是一道很常見的面試題。在Python中實現(xiàn)起來非常簡單,。 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
上面的實現(xiàn)其實已經(jīng)能滿足大多數(shù)情況,但是并不完美。比如第二個字符串中的感嘆號并沒有被翻轉(zhuǎn),而且原字符串中的空格數(shù)量也沒有保留,。(在上面的例子里其實Hello和World之間不止一個空格) 我們期望的結(jié)果應該是這樣子的。 print reverse_string_by_word(s) # Expected: !World Hello
要改進上面的方案還不把問題復雜化,,推薦使用re 模塊,。你可以查閱re.split() 的官方文檔。我們看一下具體例子,。 >>> 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 <>
一句話搞定,,so easy!
(完)
看完本文有收獲,?請轉(zhuǎn)發(fā)分享給更多人 關注「Python那些事」,,做全棧開發(fā)工程師
|