How to convert comma separated string enclosed in quotes, with spaces to a list with separate elements
Why don't you try something like this?
import re
String_tobe_Tested = " 'hello', 'Ruper's', 'how am i and', 'are','you'"
String_tobe_Tested = String_tobe_Tested.lstrip(' ')
String_tobe_Tested = String_tobe_Tested[1:-1]
print(String_tobe_Tested)
String_tobe_Tested = String_tobe_Tested.strip('"')
#String_tobe_Tested = eval(String_tobe_Tested)
#String_tobe_Tested = String_tobe_Tested.split("','")
String_tobe_Tested = re.compile("','|', '").split(String_tobe_Tested)
print(String_tobe_Tested)
print(len(String_tobe_Tested))
Join a list of strings such that each string is within quotes and comma separated
Do not use this for SQL query generation. Use the database driver SQL parameters instead. You cannot hope to properly escape your way out of SQL injection attacks otherwise.
If you need to use a WHERE .. IN ..
test, generate placeholders:
query = 'SELECT * FROM table WHERE column IN ({})'.format(','.join(['%s'] * len(lst)))
cursor.execute(query, lst)
For everything else, use a list comprehension to add the quotes to the values, then join the results with commas:
', '.join(['"{}"'.format(value) for value in lst])
Demo:
>>> lst = ['John','Jack','Martin']
>>> ', '.join(['"{}"'.format(value) for value in lst])
'"John", "Jack", "Martin"'
>>> print ', '.join(['"{}"'.format(value) for value in lst])
"John", "Jack", "Martin"
This will consistently use "
double quotes; simply use "'{}'"
as the template if you must have single quotes instead.
join string by comma and put quotes around each element
In a single line using the split
and join
methods with a list comprehension.
s = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'
print(', '.join([f'"{w}"' for w in s.split(',')]))
# '"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"'
Related Topics
How to Execute Two Commands in Terminal Using Python'S Subprocess Module
Using Condition to Split Pandas Column of Lists into Multiple Columns.
How to Completely Remove Python from a Windows Machine
Tkinter: How to Use Threads to Preventing Main Event Loop from "Freezing"
Calling a Function of a Module by Using Its Name (A String)
How to Clear Your Printed Text in Python
Replacing Blank Values (White Space) With Nan in Pandas
Python Pandas Valueerror Arrays Must Be All Same Length
Regular Expression: Match Everything After a Particular Word
How to Remove Parentheses from a String
Using Selenium in Python to Save a Webpage on Firefox
Python Json.Loads Valueerror, Expecting Delimiter
Pyspark: How to Duplicate a Row N Time in Dataframe
Pandas Filtering for Multiple Substrings in Series
Programme to Print Mulitples of 5 in a Range Specified by User
Splitting a Phone Number into a List of Digits: Python
How to Constantly Run Python Script in the Background on Windows