Python 如何删除字符串中的所有前导空格
字符串是一组可以表示单词或整个句子的字符。在Python中,使用字符串非常简单,因为它们不需要显式声明,并且可以带有或不带有指定符号。
为了操作和访问字符串,Python提供了内置函数和方法,这些函数和方法位于“ String ”类下。使用这些方法,您可以对字符串执行各种操作。
本文将重点介绍如何在Python中删除字符串中的所有前导空格。
使用lstrip()函数
基本的方法是使用内置的Python字符串库中的 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()方法来删除前导空格。在这种方法中,我们将所有空格替换为null字符(‘’)。
此函数的主要缺点是,字符串之间的空格也会被删除,所以它通常不被使用。
示例
以下是一个示例-
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