简体   繁体   English

将列表转换成逗号分隔并在python中添加引号

[英]Converting a list into comma separated and add quotes in python

I have : 我有 :

val = '[12 13 14 16 17 18]'

I want to have: 我希望有:

['12','13','14','16','17','18']

I have done 我已经做好了

x = val.split(' ')
y = (" , ").join(x)

The result is 结果是

'[12 , 13 , 14 , 16 , 17 , 18 ]'

But not the exact one also the quotes 但也不是确切的引号

What's the best way to do this in Python? 在Python中执行此操作的最佳方法是什么?

你可以做到

val.strip('[]').split()

Only if you can handle a regex : 仅当您可以处理regex

import re

val = '[12 13 14 16 17 18]'
print(re.findall(r'\d+', val))

# ['12', '13', '14', '16', '17', '18']
>>> val
'[12 13 14 16 17 18]'
>>> val.strip("[]").split(" ")
['12', '13', '14', '16', '17', '18']

You can use this: 您可以使用此:

val = '[12 13 14 16 17 18]'
val = val[1:-1].split()
print(val)

Output: 输出:

['12', '13', '14', '16', '17', '18']

if you realy need the paranthesis 如果您真的需要戴面具

val = '[12 13 14 16 17 18]'
val = val.replace('[','')
val = val.replace(']','')
val = val.split(' ')

You can use ast.literal_eval after replacing whitespace with comma: 您可以在用逗号替换空格后使用ast.literal_eval

from ast import literal_eval

val = '[12 13 14 16 17 18]'
res = list(map(str, literal_eval(val.replace(' ', ','))))

print(res, type(res))

['12', '13', '14', '16', '17', '18'] <class 'list'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python字符串列表到1个字符串,用逗号和引号(,&“)分隔 - Python list of strings to 1 string separated by comma & quotes (, & ") 使用 python 中的引号解析逗号分隔的 csv 文件 - parse comma separated csv file with quotes in python 将地址列表转换为逗号分隔列表 - Converting a list of addresses to a comma separated list 将逗号分隔的字符串转换为列表但忽略引号中的逗号 - Transform comma separated string into a list but ignore comma in quotes Pandas:逗号分隔的 Excel 单元格未转换为列表 - Pandas: Comma Separated Excel Cells not Converting to List 如何避免使用逗号分隔的字符串从python中的列表中加入引号 - How to avoid quotes from a comma separated string joined from a list in python 如何将逗号分隔的字符串转换为用引号''括起来的每个单词到 python 中的列表? - How to convert a comma separated string with each word enclosed in quotes ' ' to a list in python? "Python\/Pandas:用逗号分隔数以千计的数字转换" - Python/Pandas: Converting numbers by comma separated for thousands 将逗号分隔的值转换为Python字典 - Converting the comma separated values to Python dictionary 将列表转换为包含双引号并用逗号分隔的单个字符串 - convert a list into a single string consisting with double quotes and separated by comma
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM