Python 如何从字符串前面最多去掉两个空格
我的字符串包含三个空格,我想保留一个。那我怎么能只去掉前两个,留下一个呢 范例Python 如何从字符串前面最多去掉两个空格,python,string,Python,String,我的字符串包含三个空格,我想保留一个。那我怎么能只去掉前两个,留下一个呢 范例 >>> _str=' boy' >>> _str.lstrip(' ') 'boy' 理想输出: ' boy' 感谢您的建议。一个非常通用的解决方案,尽管不是一行: def strip_n_chars(s, n, char): """Remove at most n of char from the start of s.""" for _ in rang
>>> _str=' boy'
>>> _str.lstrip(' ')
'boy'
理想输出:
' boy'
感谢您的建议。一个非常通用的解决方案,尽管不是一行:
def strip_n_chars(s, n, char):
"""Remove at most n of char from the start of s."""
for _ in range(n):
if s[0] == char:
s = s[1:]
else:
break
return s
用法示例:
>>> strip_n_chars(" foo", 2, " ")
' foo'
>>> strip_n_chars(" bar", 2, " ")
'bar'
下面是一种正则表达式方法:
import re
# 0, 1, or 2 spaces followed by a non-matched space
reg = re.compile("^([ ]{,2})(?= )")
def strip_spaces(s):
"""
Return string with 0, 1, or 2 leading spaces removed
(but leave one leading space)
"""
return reg.sub("", s)
这就像
strip_spaces("test") # => "test"
strip_spaces(" test") # => " test"
strip_spaces(" test") # => " test"
strip_spaces(" test") # => " test"
strip_spaces(" test") # => " test"
(如果你真的喜欢一行,你可以试试
from functools import partial
import re
strip_spaces = partial(re.compile("^([ ]{,2})(?= )").sub, "")
编辑:(耸耸肩)好吧,我误解了您想要的内容;使用“^([]{,2})”
代替(匹配0、1或2个空格),结果是
strip_spaces("test") # => "test"
strip_spaces(" test") # => "test"
strip_spaces(" test") # => "test"
strip_spaces(" test") # => " test"
strip_spaces(" test") # => " test"
尽管不需要前瞻性会消除正则表达式的大部分正当性。
+\u str.lstrip(“”)
?也许您想要\u str(“”,,,1)
?如果有三个以上的空格,则替换(“”,,)将不起作用。这个问题意味着最多应该删除两个空格。只需\u str[2:]如果你从(“”)开始,否则,非常感谢你。第一个很好,足够了。谢谢你的解决方案,它完全符合我的要求,但不是一行代码。@Tiger1“太多编码”?你是什么意思?当空白只有一个时,你的解决方案不起作用。JonSharpe解决方案很好。