如何在Python中去除前导空白?

258 投票
7 回答
500999 浏览
提问于 2025-04-15 12:04

我有一段文本,它的开头有一些空格,这些空格的数量在2到4个之间。

有没有简单的方法可以去掉这些开头的空格呢?(也就是说,去掉某个字符之前的所有内容?)

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

7 个回答

30

如果你想去掉一个词前后的空格,但保留中间的空格。
你可以使用:

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

这个函数 strip 会把一个字符串开头和结尾的空格去掉。

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

这样就会把 my_str 设置为 "text"

443

lstrip() 方法可以去掉字符串开头的空格、换行符和制表符。

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

编辑

正如 balpha 在评论中提到的,如果你只想去掉字符串开头的空格,可以使用 lstrip(' ')

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

相关问题:

撰写回答