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

如何从指定Python字符串中提取被!包裹的目标内容?

提取Python字符串中被!包裹的内容

针对你的需求,这里提供两种实用的实现方法:

方法一:正则表达式(通用型,适合多组!或复杂场景)

使用Python的re模块匹配被!包裹的内容,非贪婪匹配能确保准确提取目标片段:

import re

a = 'This is an example string that has a code !3377! this is the code I want to extract'
match_result = re.search(r'!(.*?)!', a)
if match_result:
    extracted_code = match_result.group(1)
    print(extracted_code)  # 输出:3377
  • 正则模式r'!(.*?)!'说明:!匹配边界符号,(.*?)是非贪婪匹配任意字符,避免匹配到多个!时的冗余内容。

方法二:字符串分割法(简单场景高效)

如果确定字符串中只有一对!,直接用split()分割后取中间部分即可:

a = 'This is an example string that has a code !3377! this is the code I want to extract'
split_parts = a.split('!')
if len(split_parts) >= 2:
    extracted_code = split_parts[1]
    print(extracted_code)  # 输出:3377
  • split('!')会将字符串按!分割为列表,目标内容恰好位于索引为1的位置。

内容的提问来源于stack exchange,提问作者Edxon20

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:10:30