日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Python 中刪除字符串中的所有空格的8種方法

 禁忌石 2023-11-18 發(fā)布于浙江
Python 中刪除字符串中的所有空格的8種方法

1. 使用Python的replace()方法

刪除空格的一種直接方法是使用replace()方法。

original_string = 'Hello, World!'no_whitespace = original_string.replace(' ', '')print(no_whitespace) # Output: 'Hello,World!'

2. 使用正則表達(dá)式

正則表達(dá)式提供了一種強(qiáng)大而靈活的方法來(lái)處理空格刪除:

import reoriginal_string = 'Remove all whitespace from this string'no_whitespace = re.sub(r'\s', '', original_string)print(no_whitespace)  # Output: 'Removeallwhitespacefromthisstring'

3. 使用列表理解

列表推導(dǎo)式提供了一個(gè)方便靈活的解決方案:

original_string = 'Python is amazing'no_whitespace = ''.join(original_string.split())print(no_whitespace) # Output: 'Pythonisamazing'”

4.使用join()方法

使用該oin()方法的另一種方法:

original_string = 'Let's remove spaces'words = original_string.split()no_whitespace = ''.join(words)print(no_whitespace)  # Output: 'Let'sremovespaces'

5.使用split()及join()方法

可以使用split()join()的組合:

original_string = 'Split and Join'no_whitespace = ' '.join(original_string.split())print(no_whitespace) # Output: 'Split and Join'

6. 使用filter()和str.isspace()

使用filter()with 函數(shù)str.isspace()來(lái)刪除空格:

original_string = '   Filter spaces   'no_whitespace = ''.join(filter(lambda x: not x.isspace(), original_string))print(no_whitespace)  # Output: 'Filterspaces'

87 刪除兩端的空格

要?jiǎng)h除字符串兩端的空格,請(qǐng)使用strip()

original_string = ' Strip spaces 'no_whitespace = original_string.strip()print(no_whitespace) # Output: 'Strip spaces'

9. 處理多行字符串

要從多行字符串中刪除空格,用splitlines()and join()

multiline_string = '''Line 1Line 2Line 3'''no_whitespace = '\n'.join(line.strip() for line in multiline_string.splitlines())print(no_whitespace)

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

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多