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)
相关问题:
Mar*_*ang 80
该函数strip将从字符串的开头和结尾删除空格.
my_str = " text "
my_str = my_str.strip()
Run Code Online (Sandbox Code Playgroud)
将设置my_str为"text".
Ten*_*zin 15
如果你想剪切单词前后的空格,但保留中间空格.
你可以使用:
word = ' Hello World '
stripped = word.strip()
print(stripped)
Run Code Online (Sandbox Code Playgroud)
Cur*_*son 11
要删除某个字符前的所有内容,请使用正则表达式:
re.sub(r'^[^a]*', '')
Run Code Online (Sandbox Code Playgroud)
删除第一个'a'的所有内容.[^a]可以替换为您喜欢的任何字符类,例如单词字符.
这个问题没有解决多行字符串,但这里是如何使用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)
我个人最喜欢的任何字符串处理是剥离、分割和连接(按顺序):
>>> ' '.join(" this is my badly spaced string ! ".strip().split())
'this is my badly spaced string !'
Run Code Online (Sandbox Code Playgroud)
一般来说,将其应用于所有字符串处理可能会很好。
这会执行以下操作: