Python中如何提取字符串内第二、第三对括号间的内容?
解决方法
方法一:正则表达式提取
直接用正则匹配所有被{}包裹的内容,再选取需要的部分拼接:
import re input_str = "{1} {John Travis} {was} {here}" # 匹配所有{}内的文本(非贪婪模式避免跨括号匹配) captured = re.findall(r'\{(.*?)\}', input_str) # 取第2、3个括号的内容(列表索引从0开始,对应1和2),用空格连接 output = ' '.join(captured[1:3]) print(output) # 输出:John Travis was
方法二:按括号分割处理
通过拆分括号来提取内容,避开内部空格的干扰:
input_str = "{1} {John Travis} {was} {here}" # 按左括号拆分,去掉第一个空元素 split_by_left = input_str.split('{')[1:] # 对每个部分按右括号拆分,取前半部分并清理多余空格 content = [item.split('}')[0].strip() for item in split_by_left] # 拼接目标内容 output = ' '.join(content[1:3]) print(output) # 输出:John Travis was
内容的提问来源于stack exchange,提问作者Álef
相关产品推荐
相关产品推荐

