久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

一道Python面試題:如何反轉(zhuǎn)字符串

 太極混元天尊 2018-05-29


來源:公眾號-哎媽呀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ā)工程師

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,,不代表本站觀點,。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,,謹防詐騙,。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報,。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多