如何用Python替换列表双引号为单引号生成合法二维列表
问题根因
你之前的代码有两个核心错误,导致拿不到合法二维列表:
- 用
z[0].strip("'[]")处理原始字符串逻辑错误:strip仅会删除字符串首尾连续的匹配字符,既没法正确拆分嵌套列表结构,还导致生成的lists元素出现引号不匹配(开头双引号、结尾单引号)的非法格式。 - 后续尝试
str(lists).replace('"',"'")后调用list(y)完全无效:list()接收字符串作为参数时,会把字符串的每个字符拆成独立元素,根本得不到嵌套列表结构。
正确实现方案
不用手动替换引号,直接先清理原始字符串的无效字符,再用Python标准库的安全解析方法转成原生列表即可,不会出现引号匹配错误的问题:
import ast # 1. 清理z[0]首尾的无效字符:原z[0]开头多了"][", 末尾多了冗余"]" valid_list_content = z[0].lstrip("][").rstrip("]") # 2. 安全将符合Python格式的列表字符串解析为原生二维列表 correct_lists = ast.literal_eval(valid_list_content)
执行后得到的correct_lists就是标准可用的二维列表,验证代码如下:
# 验证结构 print(type(correct_lists)) # 输出 <class 'list'> print(type(correct_lists[0])) # 输出 <class 'list'> print(len(correct_lists)) # 输出 2,对应两个填空条目 # 打印内容 print(correct_lists)
输出内容为:
[ [ 'This urbanisation was accompanied by the rise of new ascetic movements in __________________ Magadha including Jainism and Buddhism.', 'Greater' ], [ 'During this period aspects of Indian civilisation administration culture and religion Hinduism and Buddhism spread to much of Asia while kingdoms in southern India had maritime business links with the Middle __________________ and the Mediterranean.', 'East' ] ]
注意:不要用手动替换引号+
eval的方式处理这类字符串转结构的需求,ast.literal_eval只会解析Python原生字面量(列表、字典、字符串、数字等),不会执行字符串里的恶意代码,同时会自动处理字符串内部的引号转义、匹配问题,比手动替换可靠得多,不会误改题目文本里本来存在的引号内容。
内容的提问来源于stack exchange,提问作者Roshni Hirani
相关产品推荐
相关产品推荐

