如何在python中拆分单个列表值,用逗号分隔

时间:2013-09-21 13:51:39

标签: python regex

added = ['hypr1005.ops.colo.cmp.com,web1234.ads.colo.cmp.com,876543,4']

上面的变量是一个列表,它包含单个值,用逗号分隔,我只想用逗号分割值并创建一个看起来像

的列表
added = ['hypr1005.ops.colo.cmp.com','web1234.ads.colo.cmp.com','876543','4']

words = added.split(',')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'

猜猜拆分仅适用于不在列表中的字符串,所以我该怎么做?

2 个答案:

答案 0 :(得分:2)

调用列表第一项(split)的added[0]方法:

>>> added = ['hypr1005.ops.colo.cmp.com,web1234.ads.colo.cmp.com,876543,4']
>>> added = added[0].split(',')
>>> added
['hypr1005.ops.colo.cmp.com', 'web1234.ads.colo.cmp.com', '876543', '4']

答案 1 :(得分:0)

为了使用split,它应该是一个字符串。

>>> added = "'hypr1005.ops.colo.cmp.com','web1234.ads.colo.cmp.com','876543','4'"
>>> words = added.split(',')
>>> words
["'hypr1005.ops.colo.cmp.com'", "'web1234.ads.colo.cmp.com'", "'876543'", "'4'"]
>>>