如何删除Python中的前导空格?

2024-04-25 19:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以空格开头的文本字符串,在2&4之间变化。

删除前导空白最简单的方法是什么?(即删除某个字符之前的所有内容?)

"  Example"   -> "Example"
"  Example  " -> "Example  "
"    Example" -> "Example"

Tags: 方法字符串文本内容example字符空白空格
3条回答

函数strip将删除字符串开头和结尾的空白。

my_str = "   text "
my_str = my_str.strip()

my_str设置为"text"

如果你想删掉单词前后的空格,但是保留中间的空格。
您可以使用:

word = '  Hello World  '
stripped = word.strip()
print(stripped)

^{}方法将删除字符串开头的前导空格、换行符和制表符:

>>> '     hello world!'.lstrip()
'hello world!'

编辑

As balpha pointed out in the comments,为了只从字符串开头删除空格,应该使用lstrip(' ')

>>> '   hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'

相关问题:

相关问题 更多 >