首页 > 解决方案 > 有没有一种简单的方法可以用`+`连接到python f-string的变量重新创建字符串?

问题描述

我目前正在重构写得不好的遗留代码,代码片段如下:

sql_tmp = (
                func_out
                + "(case when "
                + self.time_name
                + ">="
                + str(int(aggFrom))
                + " and "
                + segm_var
                + " = '"
                + segment
                + "'"
                + " then "
                + colName
                + " end)"
            )

或者

 print(
 "Variable",
 newColName,
 "fill share <",
 str(self.min_fill_share),
 "(",
 self.nr_columns_done_print,
 "/",
 self.nr_columns_total,
 ")",
 )

我想有一种简单的方法将这些字符串重新格式化为 Python f-string。

AFAIK PyCharm 有一种方法可以"".format()将字符串类型重做为 f 字符串,但它不适用于加号。

有没有简单的方法来实现这一目标?

标签: pythonpython-3.xvisual-studio-codef-string

解决方案


我决定编写自己的脚本,并将代码片段粘贴到长字符串中。

"".join([
    # creating f-string variable, if the string has no " on side of it
    "{" + stripped + "}"

    if '"' not in stripped[0]

    # removing "
    else stripped.replace('"', "")
    for stripped in [
        # removing whitespace and dividing the string by '+'
        x.strip() for x in " ".join(code_snippet.split()).split("+") 
    ]
])

推荐阅读