Reputation: 3288
I am using python regular expressions. I want all colon separated values in a line.
e.g.
input = 'a:b c:d e:f'
expected_output = [('a','b'), ('c', 'd'), ('e', 'f')]
But when I do
>>> re.findall('(.*)\s?:\s?(.*)','a:b c:d')
I get
[('a:b c', 'd')]
I have also tried
>>> re.findall('(.*)\s?:\s?(.*)[\s$]','a:b c:d')
[('a', 'b')]
Upvotes: 0
Views: 563
Reputation: 2210
You may use
list(map(lambda x: tuple(x.split(':')), input.split()))
where
input.split()
is
>>> input.split()
['a:b', 'c:d', 'e:f']
lambda x: tuple(x.split(':'))
is function to convert string to tuple 'a:b' => (a, b)
map
applies above function to all list elements and returns a map object (in Python 3) and this is converted to list using list
Result
>>> list(map(lambda x: tuple(x.split(':')), input.split()))
[('a', 'b'), ('c', 'd'), ('e', 'f')]
Upvotes: 1
Reputation: 101
The following code works for me:
inpt = 'a:b c:d e:f'
re.findall('(\S+):(\S+)',inpt)
Output:
[('a', 'b'), ('c', 'd'), ('e', 'f')]
Upvotes: 2
Reputation: 6781
The easiest way using list comprehension
and split
:
[tuple(ele.split(':')) for ele in input.split(' ')]
#driver values :
IN : input = 'a:b c:d e:f'
OUT : [('a', 'b'), ('c', 'd'), ('e', 'f')]
Upvotes: 1
Reputation: 3186
Use split instead of regex, also avoid giving variable name like keywords :
inpt = 'a:b c:d e:f'
k= [tuple(i.split(':')) for i in inpt.split()]
print(k)
# [('a', 'b'), ('c', 'd'), ('e', 'f')]
Upvotes: 2