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

如何用Python正则为print行添加括号并优化替换逻辑?

Python2 转 Python3 print语句的优雅正则替换方案

问题背景

要把Python 2里不带括号的print语句(比如print "*** Dictionaries"、print dictionaries)改成Python 3的print()函数格式,还要跳过已经是print(xxx)的行,同时得避免出现print((bestMatch))这种重复括号的坑。

正则替换实现方案

直接用re.sub就能优雅搞定,分基础版和优化版:

基础版(处理无括号的print语句)

先搞定最常见的纯无括号print场景:

import re

# 正则匹配行首缩进 + print + 空格 + 非括号开头的内容
pattern = r'^(\s*)print\s+(?!\()(.*)$'
# 替换成 缩进 + print(内容)
replacement = r'\1print(\2)'

# 示例用法
code = """
print "*** Dictionaries"
print dictionaries
print(bestMatch)
"""
updated_code = re.sub(pattern, replacement, code, flags=re.MULTILINE)
print(updated_code)

输出结果:

print("*** Dictionaries")
print(dictionaries)
print(bestMatch)

正则里的(?!\()是核心——负向预查,确保print后面不是左括号,直接跳过已经符合Python3格式的行。

优化版(避免重复括号)

如果遇到print (bestMatch)这种Python2里带空格的括号写法,基础版会生成print((bestMatch)),所以加个分支处理这种情况:

import re

pattern = r'^(\s*)print\s+(?:\((.*)\)|(?!\()(.*))$'

# 用lambda判断场景,避免重复括号
def replace_func(match):
    indent = match.group(1)
    content_in_paren = match.group(2)
    content_raw = match.group(3)
    # 优先取括号内的内容(处理带空格的冗余括号),否则用原内容
    target_content = content_in_paren if content_in_paren else content_raw
    return f"{indent}print({target_content})"

# 示例用法
code = """
print "*** Dictionaries"
print dictionaries
print(bestMatch)
print (bestMatch)
"""
updated_code = re.sub(pattern, replace_func, code, flags=re.MULTILINE)
print(updated_code)

输出结果:

print("*** Dictionaries")
print(dictionaries)
print(bestMatch)
print(bestMatch)

这个版本覆盖了两种情况:既处理纯无括号的print,又把print (xxx)这种冗余括号的写法直接转成标准的print(xxx)。

额外说明

  • 用flags=re.MULTILINE是让^和$匹配每一行的首尾,而非整个文本的首尾
  • 对于Python2里带逗号的print(比如print a, b),替换后会变成print(a, b),正好符合Python3的print函数语法
  • 如果遇到多行的print语句(比如带反斜杠换行的),这个正则可能无法处理,但大部分单文件里的print都是单行的,足够应付日常需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 08:25:19