簡體   English   中英

如何將python源文件中的字符串轉換為多行字符串?

[英]How to transform strings in a python source-file to multiline strings?

為了提高Python代碼庫的可讀性,我想對所有包含換行符的字符串進行轉換,以將其轉換為多行字符串。 例如

foo = 'line 1\nline2\nline3'

應轉換為:

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.

這樣可以解決您的未解決問題嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM