You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 16:30:58