提问人:LennartPfeiler 提问时间:5/24/2023 最后编辑:LennartPfeiler 更新时间:5/24/2023 访问量:68
Python:将多个带有分隔符的字符串保存在一个变量中
Python: Save multiple strings with separator in one variable
问:
为了在我的 SQL 语句中包含一个变量,我需要一个存储几个月的变量。
我命名了它,我不会在这里复制整个 SQL 语句,因为它与问题无关,但这里有一个片段,应该在其中使用该变量:months
...
FROM database
year = '{current_year}'
AND month IN ({months})
...
变量应如下所示的示例如下:
Ex 1: months = '1', '2', '3'
Ex 2: months = '1', '2', '3', '4', '5', '6'
这取决于上个月,有多少数字被保存为字符串,所以它是动态的。因此,我无法将每个月保存在一个变量中并添加它。 到目前为止,我已经将月份添加为一个列表。
current_month = datetime.now().month
last_month = current_month -1
for x in range(last_month):
x+=1
monthList.append(x)
months = ", ".join( repr(e) for e in monthList )
问题是,单个数字具有数据类型字符串,但缺少引号,因此 SQL 语句被正确执行。 我也对一个完全不同的解决方案持开放态度,我只需要变量的正确格式。
答:
1赞
harsh bangari
5/24/2023
#1
您可以使用 str(),然后对字符串(第一个和最后一个)进行切片,通过从列表中删除 [] 来获得所需的结果。
def modify_list(input):
string_without_brackets = str(input)[1:-1]
return string_without_brackets
item_list = ['jan', 'feb', 'mar', 'apr','may']
final_result = modify_list(item_list)
print(final_result)
//Output
'jan', 'feb', 'mar', 'apr','may'
评论
0赞
matszwecja
5/24/2023
这是将列表转换为字符串的一种非常混乱的方法。
1赞
matszwecja
5/24/2023
#2
current_month = 5
months = ", ".join(f"'{m}'" for m in range(current_month))
print(months) # '0', '1', '2', '3', '4'
评论
", ".join(str(i) for i in range(last_month))