1

lets say I have a string like this:

"ID: 123 Name: Michael , ID: 124 Name: John" 

I want to extract all of the ID's like a list which is the word between "ID:" and "Name:"

My desired output:

output = ['123', '124']

How can I do this most efficiently? Thank you very much=)

2 Answers 2

4

You can use re.findall here. You can extract Number between 'ID: number Name:.

s=" ID: 123 Name: Michael , ID: 124 Name: John "
re.findall(r'ID: (\d+) Name',s)
# ['123', '124']

Regex pattern explanation r'ID: (\d+) Name' You can read about regex Syntax

  • \d+ is used to capture numbers
  • () is used to capture the pattern enclosed between them.
  • re.findall Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

I would suggest using a dictionary instead of storing details in a string.

details={'123':'Micheal','124':'John'}

Since every ID would be unique you can use it a key and Name as value corresponding to the key.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

[ i for i in " ID: 123 Name: Michael , ID: 124 Name: John ".split() if i.isnumeric()]

gives the output:

['123', '124']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.