I want to replace a string ('None') with NULL without quote.
For example:
data = ('a','None','1','None')
And desired result:
result = "'a', NULL, '1', NULL"
Is there a way to get the expected result? Thanks in advance!!
CodePudding user response:
You can use join
to build the resulting string:
data = ('a','None','1','None')
t = ', '.join('NULL' if t == 'None' else repr(t) for t in data)
t
is then the string "'a', NULL, '1', NULL"
.
But I really cannot imagine a real world use case for that...
CodePudding user response:
NULL is not a valid keyword in Python. Instead, you use None
. In addition, you cannot modify a Tuple.
If you are using a list, however;
data[1] = None
CodePudding user response:
Use a generator comprehension along with the tuple()
function:
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)
If you want your final result to be a comma-seperated string of values, use this:
# 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)