Home > Net >  Difficult in converting to strings from a list
Difficult in converting to strings from a list

Time:10-08

I have a list which is in below format

A = [ "machine's code" ,"max's code"]

I want to convert to that list to string and pass it to a query. I am using python for this.

I am trying with below query and not giving required results

for i in A:query=Select * from table where name='" str(A) "'"

Expected code should be : Select * from table where name="machine's code"

CodePudding user response:

if your list really only has one element, then the normal array indexing works inside an f-string:

 query = f"Select * from table where name='{A[0]}'"

CodePudding user response:

Does this answer your question?

# List of queries
select_list = [f'Select * from table where name="{a}"' for a in A]
print(*select_list, sep=' ; ')  # Select * from table where name="machine's code" ; Select * from table where name="max's code"

# IN operator
join_str = '", "'
select_in = f'Select * from table where name in ("{join_str.join(a for a in A)}")'
print(select_in)  # Select * from table where name in ("machine's code", "max's code")

# OR operator
join_str = '" or name="'
select_or = f'Select * from table where name="{join_str.join(a for a in A)}"'
print(select_or) # Select * from table where name="machine's code" or name="max's code"

Careful, you may use simple quote instead of double quote in SQL requests, no?

  • Related