You need to enable JavaScript to run this app. 如何在Python中使用replace和切片操作替换字符串中ACC后缀的课程编号
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中使用replace和切片操作替换字符串中ACC后缀的课程编号

解答

你提到的写法无法实现需求,Python 原生的str.replace()仅支持精确匹配固定字符串,不支持通配符匹配动态的4位课程编码,因此my_string.replace(ACC ****, ACC + course_code)的写法不能正常运行。

正确实现方案需要用到Python标准库的正则表达式模块re,示例代码如下:

import re

# 原字符串与变量定义
my_string = "Once upon a time, there was a boy. He went to school and enrolled to a course ACC 2011, Later he enrolled to another course ACC 4589. He did well in both of the courses"
course_code = 1111

# 匹配所有「ACC + 空格 + 4位数字」的内容并替换
new_string = re.sub(r'ACC \d{4}', f'ACC {course_code}', my_string)

运行后输出的new_string就是你需要的结果:

"Once upon a time, there was a boy. He went to school and enrolled to a course ACC 1111, Later he enrolled to another course ACC 1111. He did well in both of the courses"

规则说明

正则表达式r'ACC \d{4}'中,\d代表匹配任意阿拉伯数字,{4}代表连续匹配4个数字,刚好匹配你场景中的课程编码格式;re.sub()默认会替换字符串中所有匹配到的内容,符合你全部替换的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 19:18:03