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

如何用正则或Pythonic方法将字符串中单引号替换为带引号的双引号?

当然可以用正则实现,而且有很Pythonic的写法!

完全没问题~用Python的re模块就能轻松搞定这个需求,比手动遍历字符串优雅多了。下面给你两种常见场景的实现方式:

场景1:仅替换独立的关键字(避免子串匹配)

如果你的关键字是独立的单词(不想匹配比如foobar里的foo),可以利用**单词边界\b**来精准匹配:

import re

def quote_keywords(text, keywords):
    # 对每个关键字转义,避免正则元字符干扰
    escaped_keywords = [re.escape(k) for k in keywords]
    # 构建正则模式:匹配任意一个关键字的独立出现
    pattern = r'\b(' + '|'.join(escaped_keywords) + r')\b'
    # 替换成带双引号的形式
    return re.sub(pattern, r'"\1"', text)

# 示例使用
text = "I love foo and bar, but not foobar or foo123"
keywords = ["foo", "bar"]
print(quote_keywords(text, keywords))
# 输出:I love "foo" and "bar", but not foobar or foo123

场景2:替换所有出现的关键字(包括子串)

如果需要匹配字符串中所有出现的关键字(哪怕是作为其他词的一部分),去掉单词边界即可:

import re

def quote_all_keywords(text, keywords):
    escaped_keywords = [re.escape(k) for k in keywords]
    pattern = r'(' + '|'.join(escaped_keywords) + r')'
    return re.sub(pattern, r'"\1"', text)

# 示例使用
text = "foobar has foo, and barista has bar"
keywords = ["foo", "bar"]
print(quote_all_keywords(text, keywords))
# 输出:"foo""bar" has "foo", and "bar"ista has "bar"

为什么这是Pythonic的?

这种写法用一行re.sub就完成了核心逻辑,利用了Python标准库的强大功能,既简洁又易读,完全符合Python“优雅、简洁”的风格~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:17:05