如何删除 Python 中的前导空格? [英] How do I remove leading whitespace in Python?

查看:57
本文介绍了如何删除 Python 中的前导空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

示例"->例子"示例"->例子  "示例"->例子"

解决方案

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

<预><代码>>>>'你好世界!'.lstrip()'你好,世界!'

编辑

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

<预><代码>>>>' hello world 有 2 个空格和一个制表符!'.lstrip(' ')'\thello world 有 2 个空格和一个制表符!'

相关问题:

I have a text string that starts with a number of spaces, varying between 2 & 4.

What is the simplest way to remove the leading whitespace? (ie. remove everything before a certain character?)

"  Example"   -> "Example"
"  Example  " -> "Example  "
"    Example" -> "Example"

解决方案

The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning:

>>> '     hello world!'.lstrip()
'hello world!'

Edit

As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string, lstrip(' ') should be used:

>>> '   hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'

Related question:

这篇关于如何删除 Python 中的前导空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆