216

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

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

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

7 回答 7

381

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!'

相关问题:

于 2009-06-06T07:57:22.113 回答
103

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

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

将设置my_str"text"

于 2009-06-06T07:58:37.850 回答
27

如果要删除单词前后的空格,但保留中间的空格。
你可以使用:

word = '  Hello World  '
stripped = word.strip()
print(stripped)
于 2015-06-12T11:47:39.350 回答
14

要删除某个字符之前的所有内容,请使用正则表达式:

re.sub(r'^[^a]*', '')

删除直到第一个“a”的所有内容。[^a]可以替换为您喜欢的任何字符类,例如单词字符。

于 2009-06-06T08:04:13.003 回答
10

这个问题没有解决多行字符串,但这里是如何使用python 的标准库 textwrap 模块从多行字符串中去除前导空格。如果我们有一个像这样的字符串:

s = """
    line 1 has 4 leading spaces
    line 2 has 4 leading spaces
    line 3 has 4 leading spaces
"""

如果我们print(s)得到如下输出:

>>> print(s)
    this has 4 leading spaces 1
    this has 4 leading spaces 2
    this has 4 leading spaces 3

如果我们使用textwrap.dedent

>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
于 2019-08-12T21:46:27.273 回答
1

清理文本时使用正则表达式是最佳实践

def removing_leading_whitespaces(text):
     return re.sub(r"^\s+","",text)

应用上述功能

removing_leading_whitespaces("  Example")
"  Example"   -> "Example"

removing_leading_whitespaces("  Example  ")
"  Example  " -> "Example  "

removing_leading_whitespaces("    Example")
"    Example" -> "Example"
于 2021-05-25T06:53:28.000 回答
1

对于任何字符串处理,我个人最喜欢的是剥离、拆分和连接(按此顺序):

>>> ' '.join("   this is my  badly spaced     string   ! ".strip().split())
'this is my badly spaced string !'

一般来说,将它应用于所有字符串处理可能会很好。

这将执行以下操作:

  1. 首先它剥离 - 这会删除前导和结束空格。
  2. 然后它会分裂 - 默认情况下它会在空格上执行此操作(因此它甚至会获得制表符和换行符)。问题是这会返回一个列表。
  3. 最后 join 遍历列表并连接每个列表,其间有一个空格。
于 2021-11-11T21:35:09.367 回答