Home > OS >  How to insert values from list into string?
How to insert values from list into string?

Time:08-09

I gave a list with values: ["a", "b", "c"]. and I have a string: "SELECT FROM db". I would like to paste all values from my list into that string after SELECT. so desired result is: "SELECT "a", "b", "c" FROM db". How could I do that?

CodePudding user response:

You could use string concatenation and string formatting:

Code:

letters = ["a", "b", "c"]

text = "SELECT FROM db"

text = text.split()

letters = ", ".join(letters)
text = f"{text[0]} {letters} {' '.join(text[1:])}"
print(text)

Output:

SELECT a, b, c FROM db

CodePudding user response:

Assuming the values in the column list are sanitized, you can use string interpolation:

columns = ["a", "b", "c"]
query = "SELECT {0} FROM db".format(','.join(columns))
print(columns)

Update: note that you should sanitize query parameters to prevent SQL injection. For example:

columns = ["a", "b", "c"]

def sanitize(input):
    """
    sanitize user input to prevent SQL injection.
    change it with a more robust sanitizion policy / library.
    """
    sanitized = []
    for i in input:
        if i.isalpha():
            sanitized.append(i)
    return sanitized

columns = sanitize(columns)
query = "SELECT {0} FROM db".format(','.join(columns))
print(query)

Output:

SELECT a,b,c FROM db
  • Related