2024-04-25 19:53:16 发布
网友
我有一个以空格开头的文本字符串,在2&4之间变化。
删除前导空白最简单的方法是什么?(即删除某个字符之前的所有内容?)
" Example" -> "Example" " Example " -> "Example " " Example" -> "Example"
函数strip将删除字符串开头和结尾的空白。
strip
my_str = " text " my_str = my_str.strip()
将my_str设置为"text"。
my_str
"text"
如果你想删掉单词前后的空格,但是保留中间的空格。 您可以使用:
word = ' Hello World ' stripped = word.strip() print(stripped)
^{}方法将删除字符串开头的前导空格、换行符和制表符:
>>> ' hello world!'.lstrip() 'hello world!'
编辑
As balpha pointed out in the comments,为了只从字符串开头删除空格,应该使用lstrip(' '):
lstrip(' ')
>>> ' hello world with 2 spaces and a tab!'.lstrip(' ') '\thello world with 2 spaces and a tab!'
相关问题:
函数
strip
将删除字符串开头和结尾的空白。将
my_str
设置为"text"
。如果你想删掉单词前后的空格,但是保留中间的空格。
您可以使用:
^{} 方法将删除字符串开头的前导空格、换行符和制表符:
编辑
As balpha pointed out in the comments,为了只从字符串开头删除空格,应该使用
lstrip(' ')
:相关问题:
相关问题 更多 >
编程相关推荐