I am trying to build create table statement using python.
my values are stored as following
strsql = ('Col1' 'TEXT'
, ' col2' 'NUMBER(38, 0)'
, 'col3' 'TEXT'
, 'col4' 'TEXT'
, 'col5' 'TIMESTAMP_NTZ')
and using below to
print(', '.join(['t.$1:' i[0] for i in strsql]))
i am getting output as t.$1:C, t.$1:C , t.$1:c, t.$1:c, t.$1:c
expectation: t.$1:Col1, t.$1:col2 , t.$1:col3, t.$1:col4, t.$1:col5
what I am missing in print statement!
CodePudding user response:
The inferred type of the strsql
variable is currently a tuple[str, ...]
.
This happens because 'Col1' 'TEXT'
actually concatenates the string into a single string value, like i = 'Col1Text'
in this case. Thus, accessing i[0]
of this value returns the first character in the string element, or C
in this case.
For a simple fix, modify your strsql
variable to be a tuple[tuple[str, str], ...]
type instead - that is, a tuple of one or more (name, type)
elements.
strsql = (('Col1', 'TEXT'),
(' col2', 'NUMBER(38, 0)'),
('col3', 'TEXT'),
('col4', 'TEXT'), ('col5', 'TIMESTAMP_NTZ'))
With this change in place, your original print
statement now prints the desired result:
t.$1:Col1, t.$1: col2, t.$1:col3, t.$1:col4, t.$1:col5
CodePudding user response:
You access the first character of each string. What you really want is to access the first part.
strsql = (('Col1', 'TEXT'), ('col2', 'NUMBER(38, 0)'), ('col3', 'TEXT'), ('col4', 'TEXT'), ('col5', 'TIMESTAMP_NTZ'))
print(', '.join(['t.$1:' col for col, _ in strsql]))
CodePudding user response:
You can slice the indiced index of character i[:4]
:
strsql = ('Col1' 'TEXT' , 'col2' 'NUMBER(38, 0)' , 'col3' 'TEXT' , 'col4' 'TEXT' , 'col5' 'TIMESTAMP_NTZ')
print(', '.join([f"t.$1:{i[:4]}" for i in strsql]))
# t.$1:Col1, t.$1:col2, t.$1:col3, t.$1:col4, t.$1:col5