简体   繁体   中英

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. 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?

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 . The code below assumes that the quotation marks are in 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM