如何在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()方法。我們將使用此方法對映空空格,然後使用split()方法將它們替換為空格。此方法沒有任何缺點。

示例

在下面給出的示例中,我們結合使用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+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告