简体   繁体   中英

Python string extraction: Extract part between two predefined strings

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=)

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.

Try this:

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

gives the output:

['123', '124']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM