代码之家  ›  专栏  ›  技术社区  ›  jubilantdollop

在Python中,如何从字符串数组的偏移量中去掉前导空格?

  •  1
  • jubilantdollop  · 技术社区  · 8 年前

    我是Python新手,但我有一个简单的问题。我知道我可以使用lstrip()从字符串中去掉前导空格/制表符。但是假设我有一个字符串str:

    str = '+        12  3' 
    

    '+12 3'
    

    我想通过在原始字符串的子字符串上调用lstrip来实现这一点:

    str[1:] = str[1:].lstrip()
    

    但我得到了以下错误:

    Traceback (most recent call last):
    File "ex.py", line 51, in <module>
    print(Solution().myAtoi('    12  3'))
    File "ex.py", line 35, in myAtoi
    str[x:] = str[x:].lstrip()
    TypeError: 'str' object does not support item assignment
    

    有没有办法使用lstrip()实现这一点?或者我应该研究另一种方法吗?

    谢谢!:D

    3 回复  |  直到 8 年前
        1
  •  3
  •   Chris    8 年前

    你可以打电话 str.lstrip 在字符串部分 之前 + ,然后将第一个字符连接回:

    >>> s = '+        12  3'
    >>> s = s[0] + s[1:].lstrip()
    >>> s
    '+12  3'
    
        2
  •  2
  •   Ajax1234    8 年前

    可以使用正则表达式:

    import re
    
    data = re.sub("(?<=\+)\s+", '', '+        12  3')
    

    输出:

    '+12  3'
    

    (?<=\+) #is a positive look-behind
    \s+ #will match all occurrences of white space unit a different character is spotted.
    
        3
  •  1
  •   Chris    8 年前

    str 是不可变类型。你 不能 在位更改现有字符串。你 可以 Christian 已经提供了构建所需字符串的详细信息。