如何在 Python 中去除字串開頭的所有空格?


字串是一系列字元,可以表示單個單詞或整個句子。字串在 Python 中易於使用,因為它們不需要顯式宣告,並且可以用或不用說明符定義。

為了操作和訪問字串,Python 在“String”類下提供了內建函式和方法。使用這些方法,您可以在字串上執行各種操作。

在本文中,我們將重點介紹如何在 python 中去除字串開頭的所有空格。

使用 lstrip() 函式

基本方法是使用內建 python 字串庫中的lstrip()函式。lstrip()函式刪除字串左側的所有不必要的空格。

我們有類似的函式rstrip()strip()

  • rstrip()函式刪除字串右側的所有空格。

  • strip()函式刪除字串左右兩側的所有空格。

示例 1

在下面給出的示例中,我們使用 lstrip() 方法執行了去除尾隨空格的操作。

str1 = "Hyderabad@1234" print("Removing the trailing spaces") print(str1.lstrip())

輸出

上面示例的輸出為:

Removing the trailing spaces
Hyderabad@1234

示例 2

在下面給出的示例中,我們使用 rstrip() 方法執行了去除開頭空格的操作。

str1 = "Hyderabad@1234 " print("Removing the leading spaces") print(str1.rstrip())

輸出

上面給出的示例的輸出為:

Removing the leading spaces
Hyderabad@1234

示例 3

在下面給出的示例中,我們使用 strip() 方法執行了去除尾隨和開頭空格的操作。

str1 = "Hyderabad@1234" print("Removing both trailing and leading spaces") print(str1.strip())

輸出

上面給出的程式的輸出為:

Removing both trailing and leading spaces
Hyderabad@1234

使用 replace() 方法

我們還可以使用字串庫中的replace()方法來去除開頭空格。在這種方法中,我們將用空字元('')替換所有空格。

此函式的主要缺點是字串之間的空格也會被刪除,因此它很少使用。

示例

以下是對此的示例:

str1 = " Welcome to Tutorialspoint" print("The given string is: ",str1) print("After removing the leading white spaces") print(str1.replace(" ",""))

輸出

('The given string is: ', '         Welcome to Tutorialspoint')
After removing the leading white spaces
WelcometoTutorialspoint

使用 join() 和 split() 方法

另一種方法是使用join()方法結合split()方法。我們將使用此方法對映空空格,然後使用spilt()方法將它們替換為空格。此方法沒有任何缺點。

示例

在下面給出的示例中,我們結合使用 join() 方法和 split() 方法執行了去除尾隨和開頭空格的操作。

str1 = " Hyderabad@1234 " print("Removing both trailing and leading spaces") print(" ".join(str1.split()))

輸出

上面給出的程式的輸出為:

Removing both trailing and leading spaces
Hyderabad@1234

更新於: 2022年10月19日

17K+ 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.