2020国产成人精品视频,性做久久久久久久久,亚洲国产成人久久综合一区,亚洲影院天堂中文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. 使用正則表達式

正則表達式提供了一種強大而靈活的方法來處理空格刪除:

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)式提供了一個方便靈活的解決方案:

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()來刪除空格:

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

87 刪除兩端的空格

要刪除字符串兩端的空格,請使用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)

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

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多