【问题标题】:Python: Split string without losing split character [duplicate]Python:拆分字符串而不会丢失拆分字符[重复]
【发布时间】:2021-07-06 00:23:14
【问题描述】:

string = 'Hello.World.!'

我的尝试

string.split('.')

输出

['你好','世界','!']

目标输出

['Hello', '.', 'World', '.', '!']

【问题讨论】:

    标签: python arrays string split python-3.9


    【解决方案1】:

    你可以这样做:

    string = 'Hello.World.!'
    
    result = []
    for word in string.split('.'):
        result.append(word)
        result.append('.')
    
    # delete the last '.'
    result = result[:-1]
    

    你也可以像这样删除列表的最后一个元素:

    result.pop()
    

    【讨论】:

    • 删除可以通过result.pop()来完成,而不是数组切片来创建一个新列表。
    【解决方案2】:

    使用re.split 并在分隔符周围放置一个捕获组:

    import re
    string = 'Hello.World.!'
    
    re.split(r'(\.)', string)
    # ['Hello', '.', 'World', '.', '!']
    

    【讨论】:

      【解决方案3】:

      使用re.split(),第一个参数作为分隔符。

      import re
      
      print(re.split("(\.)", "hello.world.!"))
      

      反斜杠是为了转义“.”因为它是正则表达式中的特殊字符,并且括号也用于捕获分隔符。

      相关问题:In Python, how do I split a string and keep the separators?

      【讨论】:

        【解决方案4】:

        如果您想在一行中执行此操作:

        
        string = "HELLO.WORLD.AGAIN."
        pattern = "."
        result = string.replace(pattern, f" {pattern} ").split(" ")
        # if you want to omit the last element because of the punctuation at the end of the string uncomment this
        # result = result[:-1] 
        
        

        【讨论】:

        • 迄今为止最好的一个
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 2011-12-31
        • 2015-05-12
        • 2010-11-03
        • 1970-01-01
        相关资源
        最近更新 更多