我有一个以多个空格开头的文本字符串,在 2 和 4 之间变化。
删除前导空格的最简单方法是什么?(即删除某个字符之前的所有内容?)
" Example" -> "Example"
" Example " -> "Example "
" Example" -> "Example"
我有一个以多个空格开头的文本字符串,在 2 和 4 之间变化。
删除前导空格的最简单方法是什么?(即删除某个字符之前的所有内容?)
" Example" -> "Example"
" Example " -> "Example "
" Example" -> "Example"
该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!'
相关问题:
该函数strip
将从字符串的开头和结尾删除空格。
my_str = " text "
my_str = my_str.strip()
将设置my_str
为"text"
。
如果要删除单词前后的空格,但保留中间的空格。
你可以使用:
word = ' Hello World '
stripped = word.strip()
print(stripped)
要删除某个字符之前的所有内容,请使用正则表达式:
re.sub(r'^[^a]*', '')
删除直到第一个“a”的所有内容。[^a]
可以替换为您喜欢的任何字符类,例如单词字符。
这个问题没有解决多行字符串,但这里是如何使用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
清理文本时使用正则表达式是最佳实践
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"
对于任何字符串处理,我个人最喜欢的是剥离、拆分和连接(按此顺序):
>>> ' '.join(" this is my badly spaced string ! ".strip().split())
'this is my badly spaced string !'
一般来说,将它应用于所有字符串处理可能会很好。
这将执行以下操作: