简体   繁体   English

通过考虑多个值来拆分字符串

[英]Split string by considering multiple values

I'm trying to split the following type of string in Python 2.7 in order to convert it into a list of values:我试图在 Python 2.7 中拆分以下类型的字符串,以便将其转换为值列表:

s = "19, '8X','1Gb', '1.5 GHz dual-core',342,'4.3', '720x1280','32,35 x 66,2 x 10,12', 130, '', 4, 9"

I would like to get a list of values similar to:我想获得类似于以下内容的值列表:

list_s = [19, '8X', '1Gb', '1.5 GHz dual-core', 342, '4.3', '720x1280', '32,35 x 66,2 x 10,12', 130, ' ', 4, 9]

I tried to used the function split() and the function re.split() in the following way:我尝试通过以下方式使用 function split()和 function re.split()

list_s = s.split(",")
#OUTPUT =  ['19', " '8X'", " '1Gb'", " '1.5 GHz dual-core'", ' 342', " '4.3'", " '720x1280'", " '32", '35 x 66', '2 x 10', "12'", ' 130', " ''", ' 4', ' 9']

list_s2 = re.split("([`]|[']|[\"]){1}[,]", s)
#OUTPUT =  ["19, '8X", "'", " '1Gb", "'", " '1.5 GHz dual-core", "'", " 342, '4.3", "'", " '720x1280", "'", " '32,35 x 66,2 x 10,12", "'", " 130, '", "'", ' 4, 9']

Can you suggest me a solution for this problem?你能建议我解决这个问题吗?

Direct eval for the fixed , raw-string works well:固定的原始字符串的直接eval效果很好:

>>> s = "19, '8X','1Gb', '1.5 GHz dual-core',342,'4.3', '720x1280','32,35 x 66,2 x 10,12', 130, '', 4, 9"
>>> list(eval(s))
[19, '8X', '1Gb', '1.5 GHz dual-core', 342, '4.3', '720x1280', '32,35 x 66,2 x 10,12', 130, '', 4, 9]

However, do look at this .不过,看看这个 eval is certainly dangerous as mentioned in the comments and should be used only on static/fixed raw-strings you are sure about.正如评论中提到的那样, eval肯定是危险的,并且应该仅用于您确定的静态/固定原始字符串。 In that case, the posted answer suggesting ast.literal_eval is the safest and correct choice.在这种情况下,建议ast.literal_eval的已发布答案是最安全和正确的选择。

It's simpler to achieve this using ast.literal_eval() :使用ast.literal_eval()更简单:

>>> s = "19, '8X','1Gb', '1.5 GHz dual-core',342,'4.3', '720x1280','32,35 x 66,2 x 10,12', 130, '', 4, 9"
>>> import ast

>>> ast.literal_eval("[{}]".format(s))
[19, '8X', '1Gb', '1.5 GHz dual-core', 342, '4.3', '720x1280', '32,35 x 66,2 x 10,12', 130, '', 4, 9]

Refer "ast.literal_eval()" document for more details.有关详细信息,请参阅“ast.literal_eval()”文档

If you are going to use any solution using regex or str.split() , then after splitting the elements into strings, you'll have to explicitly type-cast the integers & floats to get your desired list.如果您要使用任何使用 regex 或str.split()的解决方案,那么在将元素拆分为字符串之后,您必须显式地对整数和浮点数进行类型转换以获得所需的列表。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM