首頁  >  文章  >  後端開發  >  如何在 Python 中刪除字串中的空格?

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

Linda Hamilton
Linda Hamilton原創
2024-10-26 01:37:27650瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn