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

我有一个以多个空格开头的文本字符串,在 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!'

相关问题:

  • Trimming a string in Python

https://stackoverflow.com/questions/959215/

相关文章:

python - 如何在 Windows 上运行多个 Python 版本

linux - 如何找出文件的 MIME 类型(Content-Type)?

linux - Ubuntu - 在启动时使用 "sudo"运行命令

python - 随机种子() : What does it do?

python - 替换大于某个值的 Python NumPy 数组的所有元素

linux - 内核栈和用户空间栈

python - 在 Alpine Linux 上安装 Pillow 时没有这样的文件或目录 "li

linux - 如何从命令行获取 nvidia 驱动程序版本?

python - 如何在 Python 中列出目录的内容?

linux - gettimeofday() 是否保证为微秒级分辨率?