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

Jam*_*hai 161 python string whitespace trim

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

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

"  Example"   -> "Example"
"  Example  " -> "Example  "
"    Example" -> "Example"
Run Code Online (Sandbox Code Playgroud)

coo*_*ird 284

lstrip()方法将删除字符串开头的前导空格,换行符和制表符:

>>> '     hello world!'.lstrip()
'hello world!'
Run Code Online (Sandbox Code Playgroud)

编辑

正如balpha在评论中指出的那样,为了从字符串的开头删除空格,lstrip(' ')应该使用:

>>> '   hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'
Run Code Online (Sandbox Code Playgroud)

相关问题:

  • 但请注意,lstrip同时删除前导*空格*,这可能更多是空格(制表符等).这通常是你想要的.如果只想删除空格和空格,请调用"bla".lstrip("") (8认同)
  • 一直编程多年,并不知道这一点,救命 (3认同)
  • 对于新的Python程序员来说,python中的字符串是不可变的可能是有用的,所以如果你使用字符串'string_a',你可能会认为string_a.lstrip()会改变字符串本身,但实际上你是需要将string_a.lstrip()的值赋给自身或新变量,例如"string_a = string_a.lstrip()". (2认同)
  • 注意:正如有 lstrip() 一样,也有 strip() 和 rstrip() (2认同)

Mar*_*ang 80

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

my_str = "   text "
my_str = my_str.strip()
Run Code Online (Sandbox Code Playgroud)

将设置my_str"text".

  • 不是答案,而是很好的补充.+1 (3认同)

Ten*_*zin 15

如果你想剪切单词前后的空格,但保留中间空格.
你可以使用:

word = '  Hello World  '
stripped = word.strip()
print(stripped)
Run Code Online (Sandbox Code Playgroud)

  • https://docs.python.org/3/whatsnew/3.0.html打印是一个函数print语句已被print()函数替换,带有关键字参数来替换旧print语句的大部分特殊语法( PEP 3105). (2认同)

Cur*_*son 11

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

re.sub(r'^[^a]*', '')
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,但他也(也许是无意中)要求解决更普遍的问题,"即在某个角色之前删除所有内容?",这就是更通用的解决方案. (10认同)
  • 我认为那个人要求"最简单,最简单的方式" (2认同)

Jay*_*mon 7

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

s = """
    line 1 has 4 leading spaces
    line 2 has 4 leading spaces
    line 3 has 4 leading spaces
"""
Run Code Online (Sandbox Code Playgroud)

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

>>> print(s)
    this has 4 leading spaces 1
    this has 4 leading spaces 2
    this has 4 leading spaces 3
Run Code Online (Sandbox Code Playgroud)

如果我们使用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
Run Code Online (Sandbox Code Playgroud)


rob*_*smt 5

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

>>> ' '.join("   this is my  badly spaced     string   ! ".strip().split())
'this is my badly spaced string !'
Run Code Online (Sandbox Code Playgroud)

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

这会执行以下操作:

  1. 首先它会删除 - 这会删除前导和结尾空格。
  2. 然后它会分裂 - 默认情况下它在空白处执行此操作(因此它甚至会获得制表符和换行符)。问题是这会返回一个列表。
  3. 最后 join 迭代列表并在每个列表之间添加一个空格。