Home > Software engineering >  Python - check if 1st element in list of tuples exists in string, if it does add 2nd element from tu
Python - check if 1st element in list of tuples exists in string, if it does add 2nd element from tu

Time:02-18

I have string values called cols that have the column name and data type:

cols

_LOAD_DATETIME datetime,
_LOAD_FILENAME string,
_LOAD_FILE_ROW_NUMBER int,
_LOAD_FILE_TIMESTAMP datetime,
ID int 

next I have this list of tuples:

comment_list = [('_LOAD_FILE_TIMESTAMP', 'TEST'), ('ID', 'ID of Account')]

I want to check if the 1st position element in comment_list exists in cols the first word of cols, if it does, add the word 'COMMENT' and the 2nd position element to cols.

so cols should now look like:

cols

_LOAD_DATETIME datetime,
_LOAD_FILENAME string,
_LOAD_FILE_ROW_NUMBER int,
_LOAD_FILE_TIMESTAMP datetime COMMENT 'TEST',
ID int COMMENT 'ID of Account'

CodePudding user response:

You can use a for loop to loop through each line in the string after calling the str.split() method on the string, and concatenate each modified string to a new string:

cols = '''_LOAD_DATETIME datetime,
_LOAD_FILENAME string,
_LOAD_FILE_ROW_NUMBER int,
_LOAD_FILE_TIMESTAMP datetime,
ID int'''

comment_list = [('_LOAD_FILE_TIMESTAMP', 'TEST'), ('ID', 'ID of Account')]

cols2 = ''
for col in cols.split(","):
    for comment in comment_list:
        strings = col.split()
        if comment[0] in strings:
            strings.append(f"COMMENT '{comment[1]}'")
            break
    cols2  = " ".join(strings)   "\n"

print(cols2)

Output:

_LOAD_DATETIME datetime
_LOAD_FILENAME string
_LOAD_FILE_ROW_NUMBER int
_LOAD_FILE_TIMESTAMP datetime COMMENT 'TEST'
ID int COMMENT 'ID of Account'

  • Related