如何将 python 源文件中的字符串转换为多行字符串?



为了提高 Python 代码库的可读性,我想对所有包含换行符的字符串应用转换到多行字符串。 例如

foo = 'line 1nline2nline3'

应转换为:

foo = '''line 1
line 2
line3'''

我认为这可以通过应用正则表达式替换来完成? 有更好的选择吗?我想到的一个是使用实际分析 python AST 并允许以不同方式重新生成代码的工具,还是这个方向矫枉过正?

知道了。 我不会重复如何识别字符串;有很多方法,正则表达式可能适合您。 将线分成三部分:pre_strmulti_strpost_str。 下面的代码假定引号在multi_str中。

tri_q = "'''"
if `n` in multi_str:
if "'''" in multi_str:
tri_q = '"""'
print(pre_str, tri_q, multi_str[1:-1], tri_q, post_str)
else:
# string is not multi-line: just dump the original text.

这能处理您的未决问题吗?

最新更新