New New - 26 days ago 21
Python Question

Python - Extract text from string

What are the most efficient ways to extract text from a string? Are there some available functions or regex expressions, or some other way?


For example, my string is below and I want to extract the IDs as well
as the ScreenNames, separately.


[User(ID=1234567890, ScreenName=RandomNameHere), User(ID=233323490, ScreenName=AnotherRandomName), User(ID=4459284, ScreenName=YetAnotherName)]


Thank you!

Edit: These are the text strings that I want to pull. I want them to be in a list.

Target_IDs = 1234567890, 233323490, 4459284
Target_ScreenNames = RandomNameHere, AnotherRandomName, YetAnotherName

Answer
import re
str = '[User(ID=1234567890, ScreenName=RandomNameHere), User(ID=233323490, ScreenName=AnotherRandomName), User(ID=4459284, ScreenName=YetAnotherName)]'
print 'Target IDs = ' + ','.join( re.findall(r'ID=(\d+)', str) )
print 'Target ScreenNames = ' + ','.join( re.findall(r' ScreenName=(\w+)', str) )

Output : Target IDs = 1234567890,233323490,4459284 Target ScreenNames = RandomNameHere,AnotherRandomName,YetAnotherName

Comments