如何从字符串中修剪空格? [英] How do I trim whitespace from a string?

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

问题描述

如何从 Python 中的字符串中删除前导和尾随空格?

例如:

"你好" -->你好"你好"-->你好"你好" -->你好"鲍勃有一只猫"-->鲍勃有一只猫"

解决方案

只有一个空格还是所有连续的空格?如果是第二个,则字符串已经有 .strip() 方法:

<预><代码>>>>'你好'.strip()'你好'>>>'你好'.strip()'你好'>>>'鲍勃有一只猫'.strip()鲍勃有一只猫">>>' Hello '.strip() # 两端的所有连续空格都去掉'你好'

如果你只需要删除一个空格,你可以这样做:

def strip_one_space(s):如果 s.endswith(" "): s = s[:-1]如果 s.startswith(" "): s = s[1:]返回>>>strip_one_space("你好")'  你好'

另外,请注意 str.strip() 也会删除其他空白字符(例如制表符和换行符).要仅删除空格,您可以指定要删除的字符作为 strip 的参数,即:

<预><代码>>>>"你好\n".strip(" ")'你好\n'

How do I remove leading and trailing whitespace from a string in Python?

For example:

" Hello " --> "Hello"
" Hello"  --> "Hello"
"Hello "  --> "Hello"
"Bob has a cat" --> "Bob has a cat"

解决方案

Just one space or all consecutive spaces? If the second, then strings already have a .strip() method:

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '   Hello   '.strip()  # ALL consecutive spaces at both ends removed
'Hello'

If you only need to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'

Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> "  Hello\n".strip(" ")
'Hello\n'

这篇关于如何从字符串中修剪空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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