简体   繁体   中英

How to strip() out a maximum of two white spaces from the front of a string

My string contains three white spaces and I would like to keep one. How then can I strip-out just the first two and leave one?

Example

>>> _str='   boy'
>>> _str.lstrip('  ')
'boy'

Ideal output:

' boy'

Thanks for your suggestions.

A very general solution, though not a one-liner:

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

Example usage:

>>> strip_n_chars("   foo", 2, " ")
' foo'
>>> strip_n_chars(" bar", 2, " ")
'bar'

Here's a regular-expression approach:

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)

which then works like

strip_spaces("test")       # => "test"
strip_spaces(" test")      # => " test"
strip_spaces("  test")     # => " test"
strip_spaces("   test")    # => " test"
strip_spaces("    test")   # => "  test"

(if you really like one-liners, you can try

from functools import partial
import re

strip_spaces = partial(re.compile("^([ ]{,2})(?= )").sub, "")

Edit: (shrug) alright, I misunderstood what you wanted; use "^([ ]{,2})" instead (matches 0, 1, or 2 spaces), results in

strip_spaces("test")       # => "test"
strip_spaces(" test")      # => "test"
strip_spaces("  test")     # => "test"
strip_spaces("   test")    # => " test"
strip_spaces("    test")   # => "  test"

although not needing the look-ahead does away with most of the justification for a regular expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM