我有一个以多个空格开头的文本字符串,在 2 和 4 之间变化。
删除前导空格的最简单方法是什么? (即删除某个字符之前的所有内容?)
" Example" -> "Example"
" Example " -> "Example "
" Example" -> "Example"
最佳答案
lstrip()
方法将删除字符串开头的前导空格、换行符和制表符:
>>> ' hello world!'.lstrip()
'hello world!'
编辑
As balpha pointed out in the comments ,为了从字符串的开头删除 only 个空格,应该使用 lstrip(' ')
:
>>> ' hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'
相关问题:
关于python - 如何删除 Python 中的前导空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/959215/