[英]How to transform strings in a python source-file to multiline strings?
To improve readability of a Python code base i want to apply a transform on all strings containing newlines to multiline strings. 为了提高Python代码库的可读性,我想对所有包含换行符的字符串进行转换,以将其转换为多行字符串。 eg 例如
foo = 'line 1\nline2\nline3'
Should be transformed to: 应转换为:
foo = '''line 1
line 2
line3'''
I assume this can be done by applying a regex substitution? 我认为可以通过应用正则表达式替换来做到这一点? Are there better options? 有更好的选择吗? One that comes to mind is using tools that actually analyze the python AST and allow to regenerate the code a bit differently, or is this direction an overkill? 我想到的是使用实际上可以分析python AST的工具,并允许以不同的方式重新生成代码,或者这个方向过大吗?
Got it. 得到它了。 I won't repeat how to recognize a string; 我将不重复如何识别字符串。 there are many ways, and regex will likely work well for you. 有很多方法,正则表达式可能会很适合您。 Split the line into three pieces: pre_str
, multi_str
, post_str
. 将行分为三部分: pre_str
, multi_str
, post_str
。 The code below assumes that the quotation marks are in multi_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.
Does that handle your open issues? 这样可以解决您的未解决问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.