我需要将像这样的字符串转换为列表,例如在字符串中没有引号''或“”的数据。
我试图创建一个列表并遍历它以添加引号。
我想知道是否有pythonic方式或已经内置的函数来做到这一点。
col_list = [col1, col2, col3, col4]
cnvrted_list = []
for col in col_list:
item = "'" + col + "'"
cnvrted_list.append(item)
print (new_list)
NameError: name 'col1' is not defined.
Expected Output should have quotes '' to these values
new_list = ['col1','col2','col3','col4']
答案 0 :(得分:0)
您可以像这样进行列表编辑:converted_list = [f"'{word}'" for word in col_list]
>>> a = ["hi", "lol", "back"]
>>> b = [f"'{word}'" for word in a]
>>> b
["'hi'", "'lol'", "'back'"]
好像col_list中的元素是变量,但是在初始化col_list的行中被调用之前尚未定义。将它们用引号引起来,将其视为字符串
答案 1 :(得分:0)
在col1,col2,col3,col4周围添加“”。
col_list = ["col1", "col2", "col3", "col4"]
cnvrted_list = []
for col in col_list:
item = "'" + col + "'"
cnvrted_list.append(item)
print (cnvrted_list)
结果是[“'col1'”,“'col2'”,“'col3'”,“'col4'”]