python - 有没有一种简单的方法可以用`+`连接到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 字符串,但它不适用于加号。
有没有简单的方法来实现这一目标?
解决方案
我决定编写自己的脚本,并将代码片段粘贴到长字符串中。
"".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("+")
]
])
推荐阅读
- php - 在 web 应用程序或 rest API 上实现图像上传和缩略图生成?
- laravel - 如何在 PHP Netbeans 中输入提示静态方法
- this - 词法 this 和对象
- python-3.x - 如何在 Python 中为导入设置别名?
- mysql - 如何在mysql中查询这个
- spring - Spring Boot Actuator 1.5.10 - 缺少 env 端点 (404)
- node.js - 需要数据和盐参数
- python - 检查 Python 字典中是否存在重复的键或值
- powershell - 服务器不愿意处理请求
- vba - 需要运行时错误“424”对象:Excel VBA