【问题标题】:Split leading whitespace from rest of string从字符串的其余部分拆分前导空格
【发布时间】:2014-11-05 03:40:12
【问题描述】:

我不确定如何准确传达我想要做的事情,但我正在尝试创建一个函数来分割我的字符串的一部分(前导空格),以便我可以用不同的方式编辑它我的脚本的一部分,然后在它被改变后再次将它添加到我的字符串中。

假设我有字符串:

"    That's four spaces"

我想拆分它,所以我最终得到:

"    " and "That's four spaces"

【问题讨论】:

  • re.split(r"^(\s+)", " That's four spaces", 1) 几乎 做你想要的,但是在返回的数组的开头有一个额外的空字符串。我想不出更好的了。

标签: python string split


【解决方案1】:

你可以使用re.match:

>>> import re
>>> re.match('(\s*)(.*)', "    That's four spaces").groups()
('    ', "That's four spaces")
>>>

(\s*) 在字符串开头捕获零个或多个空白字符,(.*) 获取其他所有字符。

请记住,尽管字符串在 Python 中是不可变的。从技术上讲,您不能编辑它们的内容;你只能创建新的字符串对象。


对于非正则表达式的解决方案,您可以尝试以下方法:

>>> mystr = "    That's four spaces"
>>> n = next(i for i, c in enumerate(mystr) if c != ' ') # Count spaces at start
>>> (' ' * n, mystr[n:])
('    ', "That's four spaces")
>>>

这里的主要工具是nextenumerategenerator expression。这个解决方案可能比 Regex 更快,但我个人认为第一个更优雅。

【讨论】:

    【解决方案2】:

    为什么不尝试匹配而不是拆分?

    >>> import re
    >>> s = "    That's four spaces"
    >>> re.findall(r'^\s+|.+', s)
    ['    ', "That's four spaces"]
    

    说明:

    • ^\s+ 匹配行首的一个或多个空格。
    • |
    • .+ 匹配所有剩余的字符。

    【讨论】:

    • 我很乐意,但我必须在没有 sys 以外的任何导入的情况下实现我的最终产品。
    【解决方案3】:

    一种解决方案是删除字符串,然后计算出您删除了多少个字符。然后,您可以根据需要“修改”字符串,并通过将空格添加回字符串来完成。我认为这不适用于制表符,但仅对于空格似乎可以完成工作:

    my_string = "    That's four spaces"
    no_left_whitespace = my_string.lstrip()
    modified_string = no_left_whitespace + '!'
    index = my_string.index(no_left_whitespace)
    final_string = (' ' * index) + modified_string
    
    print(final_string) #     That's four spaces!
    

    还有一个简单的测试来确保我们做对了,它通过了:

    assert final_string == my_string + '!'
    

    【讨论】:

    • 拥有no_left_whitespace后,您可以直接访问left_whitespace = my_string[:len(my_string)-len(no_left_whitespace)],无需任何中介。
    【解决方案4】:

    你可以做的一件事是用字符串列出一个列表。那就是

    x="    That's four spaces"
    y=list(x)
    z="".join(y[0:4]) #if this is variable you can apply a loop over here to detect spaces from start
    k="".join(y[4:])
    s=[]
    s.append(z)
    s.append(k)
    print s
    

    这是一个非正则表达式解决方案,不需要任何导入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 2016-10-20
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多