【问题标题】:Replace slice of string python with string of different size, but maintain structure用不同大小的字符串替换字符串 python 的切片,但保持结构
【发布时间】:2018-11-24 19:57:33
【问题描述】:

所以今天我正在开发一个函数,该函数从数据块中删除任何带引号的字符串,并将它们替换为格式区域({0}{1} 等...)。
我遇到了一个问题,因为输出变得完全混乱,就像{1} 出现在一个看似随机的地方。
后来我发现这是一个问题,因为替换列表中的切片更改了列表,因此它的长度不同,因此之前的 re 匹配不会对齐(它仅适用于第一次迭代)。 正如预期的那样,字符串的收集工作完美,因为这肯定不是re 的问题。
我已经阅读了about mutable sequences,以及许多其他内容,但在这方面找不到任何内容。
我认为我需要的是类似str.replace 但可以切片,而不是子字符串。
这是我的代码:

import re

def rm_strings_from_data(data):
    regex = re.compile(r'"(.*?)"')
    s = regex.finditer(data)
    list_data = list(data)
    val = 0
    strings = []

    for i in s:
        string = i.group()
        start, end = i.span()
        strings.append(string)
        list_data[start:end] = '{%d}' % val
        val += 1

    print(strings, ''.join(list_data), sep='\n\n')

if __name__ == '__main__':
    rm_strings_from_data('[hi="hello!" thing="a thing!" other="other thing"]')

我明白了:

['"hello!"', '"a thing!"', '"other thing"']

[hi={0} thing="a th{1}r="other thing{2}

我想要输出:

['"hello!"', '"a thing!"', '"other thing"']

[hi={0} thing={1} other={2}]

任何帮助将不胜感激。谢谢你的时间:)

【问题讨论】:

    标签: string python-3.x slice


    【解决方案1】:

    为什么不使用这样的正则表达式捕获组匹配key=value 部分:(\w+?)=(".*?")
    然后根据需要组装列表变得非常容易。

    Sample Code:

    import re
    
    def rm_strings_from_data(data):
        regex = re.compile(r'(\w+?)=(".*?")')
        matches = regex.finditer(data)
        strings = []
        list_data = []
        for matchNum, match in enumerate(matches):
            matchNum = matchNum + 1
            strings.append(match.group(2))
            list_data.append((match.group(1) + '={' + str(matchNum) + '} '))
    
        print(strings, '[' + ''.join(list_data) + ']', sep='\n\n')
    
    if __name__ == '__main__':
        rm_strings_from_data('[hi="hello!" thing="a thing!" other="other thing"]')
    

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 1970-01-01
      • 2013-10-31
      • 1970-01-01
      • 2013-06-25
      • 2018-11-26
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多