Reputation: 125
I have this code to concatenated values to a string. Why is it that that my boolean value from bool_value is return Twice?
print example: 'ABCDE123','2021-03-06 12:28:45.264250',25.67,TrueTrue,2000
I expect it to return 'ABCDE123','2021-03-06 12:23:30.493241',25.67,True,2000
Thank you
EUI = 'ABCDE123'
datetime = str(dt.now())
temperature = 25.67
bool_value = True
integer_value = 2000
col_names = ['EUI', 'datetime', 'temperature', 'bool', 'integer_value']
col_values = [EUI, datetime, temperature, bool_value, integer_value]
len_col = len(col_names)
if len_col > 0:
col_names_str = ''
col_values_str = ''
for_count = 1
for x in range(len_col):
col_names_str += col_names[x]
if isinstance(col_values[x], str) : col_values_str += f"'{col_values[x]}'"
if isinstance(col_values[x], int) : col_values_str += str(col_values[x])
if isinstance(col_values[x], float) : col_values_str += str(col_values[x])
if isinstance(col_values[x], bool) : col_values_str += str(col_values[x])
if for_count < len_col:
col_names_str += ','
col_values_str += ','
for_count = for_count + 1
print(col_names_str)
print(col_values_str)
Upvotes: 0
Views: 80
Reputation: 1455
1 and 0 represent True and False. as @kaya3 mentioned bool is a subclass of int, so adding it twice.
x = 1
print(isinstance(x, int))
x = True
print(isinstance(x, int))
x = True
print(isinstance(x, bool))
Upvotes: 1
Reputation: 51037
Because bool
is a subclass of int
, so you're adding it twice.
It looks like what you actually want to do would be simpler using ','.join
and repr
:
col_names_str = ','.join(col_names)
col_values_str = ','.join(repr(x) for x in col_values)
Upvotes: 2