如何在 Python 中刪除字串中的空格?

Linda Hamilton
發布: 2024-10-26 01:37:27
原創
667 人瀏覽過

How to Remove Whitespace from a String in Python?

在Python 中修剪空格

問題:如何從字串中刪除空格(空格和製表符) Python?

答案:

Python 中有多種方法可用於修剪字串中的空格:

1. str.strip( )

str.strip() 方法刪除字串左側和右側的空格。例如:

<code class="python">s = "  \t a string example\t  "
s = s.strip()
print(s)  # Output: "a string example"</code>
登入後複製

2。 str.rstrip()

str.rstrip() 方法只刪除字串右邊的空格:

<code class="python">s = s.rstrip()
print(s)  # Output: "a string example"</code>
登入後複製

3. str.lstrip()

str.lstrip() 方法只刪除字串左邊的空格:

<code class="python">s = s.lstrip()
print(s)  # Output: "a string example  "</code>
登入後複製

4。 str.strip(chars)

您也可以使用str.strip(chars) 方法指定要剝離的特定字元集:

<code class="python">s = s.strip(' \t\n\r')
print(s)  # Output: "astringexample"</code>
登入後複製

這將刪除所有空格字串兩側的、t、n 或r 字元。

5. re.sub

此外,您可以使用正規表示式模組(re) 從字串中刪除空格:

<code class="python">import re
print(re.sub('[\s+]', '', s))  # Output: "astringexample"</code>
登入後複製

此正規表示式將取代任意數量的空格一個空字串,有效地修剪空格。

以上是如何在 Python 中刪除字串中的空格?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!