Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 用不同大小的字符串替换字符串python的切片,但保持结构不变_String_Python 3.x_Slice - Fatal编程技术网

String 用不同大小的字符串替换字符串python的切片,但保持结构不变

String 用不同大小的字符串替换字符串python的切片,但保持结构不变,string,python-3.x,slice,String,Python 3.x,Slice,因此,今天我正在开发一个函数,该函数从数据块中删除任何带引号的字符串,并将其替换为格式区域({0},{1},等等)。 我遇到了一个问题,因为输出变得完全混乱,就像在{1}中的一个看似随机的地方一样。 后来我发现这是一个问题,因为替换列表中的切片改变了列表,因此列表的长度不同,因此之前的re匹配将无法对齐(它只在第一次迭代中起作用)。 字符串的收集工作正常,正如预期的那样,因为这肯定不是re的问题 我读过,还有很多其他的东西,但是没有找到任何关于这个的东西。 我想我需要的是类似于str.repla

因此,今天我正在开发一个函数,该函数从数据块中删除任何带引号的字符串,并将其替换为格式区域(
{0}
{1}
,等等)。
我遇到了一个问题,因为输出变得完全混乱,就像在
{1}
中的一个看似随机的地方一样。
后来我发现这是一个问题,因为替换列表中的切片改变了列表,因此列表的长度不同,因此之前的
re
匹配将无法对齐(它只在第一次迭代中起作用)。
字符串的收集工作正常,正如预期的那样,因为这肯定不是
re
的问题
我读过,还有很多其他的东西,但是没有找到任何关于这个的东西。
我想我需要的是类似于
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}]

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

为什么不使用正则表达式捕获组来匹配这两个
key=value
部分:
(\w+?)=(“*?”)

然后,根据需要组合列表变得非常容易

:

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"]')