【发布时间】: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