如何从同一行中提取冒号分隔的值?

时间:2018-08-10 09:24:54

标签: python regex

我正在使用python正则表达式。我希望一行中所有用冒号分隔的值。

例如

input = 'a:b c:d e:f'

expected_output = [('a','b'), ('c', 'd'), ('e', 'f')]

但是当我这样做

>>> re.findall('(.*)\s?:\s?(.*)','a:b c:d')

我明白了

[('a:b c', 'd')]

我也尝试过

>>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d')
[('a', 'b')]

4 个答案:

答案 0 :(得分:2)

使用split而不是regex,也要避免给变量名称加上关键字  :

inpt = 'a:b c:d e:f'
k= [tuple(i.split(':')) for i in inpt.split()]
print(k)

# [('a', 'b'), ('c', 'd'), ('e', 'f')]

答案 1 :(得分:2)

以下代码对我有用:

inpt = 'a:b c:d e:f'
re.findall('(\S+):(\S+)',inpt)

输出:

[('a', 'b'), ('c', 'd'), ('e', 'f')]

答案 2 :(得分:1)

使用list comprehensionsplit的最简单方法:

[tuple(ele.split(':')) for ele in input.split(' ')]

#driver值:

IN : input = 'a:b c:d e:f'
OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')]

答案 3 :(得分:1)

您可以使用

list(map(lambda x: tuple(x.split(':')), input.split()))

其中

input.split()

>>> input.split()
['a:b', 'c:d', 'e:f']

lambda x: tuple(x.split(':'))用于将字符串转换为元组'a:b' => (a, b)

map将上述函数应用于所有列表元素,并返回一个映射对象(在Python 3中),并使用list将其转换为列表。

结果

>>> list(map(lambda x: tuple(x.split(':')), input.split()))
[('a', 'b'), ('c', 'd'), ('e', 'f')]