Computer >> Computer tutorials >  >> Programming >> Python

How to extract a substring from inside a string in Python?


You can use group capturing in regular expressions to extract a substring from inside a string. You need to know the format and surrounding of the substring you want to extract. For example if you have a line and want to extract money information from it with the format $xxx,xxx.xx you can use the following:

import re
text = 'The phone is priced at $15,745.95 and has a camera.'
m = re.search('(\$[0-9\,]*.[0-9]{2})', text)
if m:
    print m.group(1)

This will give the output:

$15,745.95

The actual regex will depend on the conditions of your use case.