我的字符串包含三个空格,我想保留一个。那我怎么能脱掉前两个并留下一个呢?
实施例
>>> _str=' boy'
>>> _str.lstrip(' ')
'boy'
理想输出:
' boy'
感谢您的建议。
答案 0 :(得分:2)
一个非常通用的解决方案,虽然不是单行:
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'
答案 1 :(得分:0)
这是一种正则表达式方法:
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"
虽然不需要预测会消除正则表达式的大部分理由。