Souradeep Nanda
Souradeep Nanda

Reputation: 3288

How to extract colon separated values from the same line?

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

Answers (4)

Swadhikar
Swadhikar

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

Jannes
Jannes

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

Kaushik NP
Kaushik NP

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

Vikas Periyadath
Vikas Periyadath

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

Related Questions