我想用不帶引號的NULL替換字串 ('None') 。
例如:
data = ('a','None','1','None')
和想要的結果:
result = "'a', NULL, '1', NULL"
有沒有辦法得到預期的結果?提前致謝!!
uj5u.com熱心網友回復:
您可以使用join來構建結果字串:
data = ('a','None','1','None')
t = ', '.join('NULL' if t == 'None' else repr(t) for t in data)
t然后是字串"'a', NULL, '1', NULL"。
但我真的無法想象一個真實世界的用例......
uj5u.com熱心網友回復:
NULL 不是 Python 中的有效關鍵字。相反,您使用None. 此外,您不能修改元組。
但是,如果您使用的是串列;
data[1] = None
uj5u.com熱心網友回復:
使用生成器理解和tuple()函式:
data = ('a', 'None', '1', 'None')
# For NULL without quotes
result = tuple(el if el is not 'None' else NULL for el in data)
# 'NULL' with quotes
result = tuple(el if el is not 'None' else 'NULL' for el in data)
如果您希望最終結果是逗號分隔的值字串,請使用以下命令:
# Replace 'NULL' with NULL if you want to reference the variable
new_result = ', '.join(el if el is not 'None' else 'NULL' for el in data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/366669.html
標籤:Python
