如何将少数名称转换为带引号的实际字符串

2024-06-25 22:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将没有引号“”或“”的类似字符串的数据转换为列表。你知道吗

我试着创建一个列表并通过它添加引号。你知道吗

我想知道是否有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']

Tags: 数据方法字符串列表newcolpythonicitem
2条回答

你可以这样做:converted_list = [f"'{word}'" for word in col_list]

>>> a = ["hi", "lol", "back"]
>>> b = [f"'{word}'" for word in a]
>>> b
["'hi'", "'lol'", "'back'"]

看起来列列表中的元素是变量,但在初始化列列表的行中被调用之前尚未定义。用引号将它们括起来,以将它们视为字符串

在列1、列2、列3、列4周围添加“”

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'”]

相关问题 更多 >