【问题标题】:Dividing string including whitespace blocks [duplicate]分割字符串,包括空格块[重复]
【发布时间】:2016-12-26 05:05:55
【问题描述】:

是否存在这样的命令,它以空格也成为字符串的方式拆分字符串?例如,假设命令是“coolsplit”:

>>> example='hey,    whats up,     how are you?'
>>> example.coolsplit()
    ['hey,','   ','whats',' ','up,','     ','how',' ','are',' ','you?'] 

它存在吗?

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    你可以re.split()捕获分隔符:

    >>> import re
    >>>
    >>> re.split(r'(\s+)', example)
    ['hey,', '    ', 'whats', ' ', 'up,', '     ', 'how', ' ', 'are', ' ', 'you?']
    

    \s+这里的意思是“一个或多个空白字符”,括号定义一个saving group

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      • 2021-06-16
      • 2022-10-13
      相关资源
      最近更新 更多