【问题标题】:Splitting a string based on the character after the delimeter - python根据分隔符后的字符拆分字符串 - python
【发布时间】:2019-02-06 00:02:27
【问题描述】:

我正在尝试根据要分割的字符之后的字符来分割字符串。例如,

k="I would like to eat you"
specialsplit(k,' ')

会返回

['I ', 'ould ', 'ike ', 'o ', 'at ', 'ou']

k="I would like to eat you"
specialsplit(k,'e')

会返回

['I would like', 'to e', 't you']

被分割的角色不会像正常的分割作品那样消失,但它之后的角色会消失。我试过了

def specialsplit(k,d):
    return [e[1:]+d if c!=0 or c==(len(k)-1) else e[:-1] if c==len(k)-1 else e+d for c,e in enumerate(k.split(d))]

但它总是将被分割的字符添加到最后一个元素,因此在第二个示例中,它返回['I would like', 'to e', 't youe'] 而不是['I would like', 'to e', 't you']。我怎么能修复这个代码,或者我怎么能解决这个问题?谢谢!

【问题讨论】:

    标签: python string list for-loop list-comprehension


    【解决方案1】:

    你可以使用re.split:

    import re
    def specialsplit(_input, _char):
      return re.split(f'(?<={_char})[\w\W]', _input)
    
    print([specialsplit("I would like to eat you", i) for i in [' ', 'e']])
    

    输出:

    [['I ', 'ould ', 'ike ', 'o ', 'at ', 'ou'], ['I would like', 'to e', 't you']]
    

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 2011-08-04
      • 2013-10-19
      • 1970-01-01
      • 2023-04-06
      • 2012-10-23
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多