How to extract colon separated values from the same line?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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')]





Can you use split ?
– Hearner
Aug 10 at 9:25




4 Answers
4



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')]





(S+)s*:s*(S+) worked for my usecase
– Souradeep Nanda
Aug 10 at 9:57



(S+)s*:s*(S+)



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')]



The easiest way using list comprehension and split :


list comprehension


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')]



You may use


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



where



input.split() is


input.split()


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



lambda x: tuple(x.split(':')) is function to convert string to tuple 'a:b' => (a, b)


lambda x: tuple(x.split(':'))


'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


map


list



Result


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS