Reputation: 19349
I need to be able to extract two numbers from a string. I know those two numbers (if presented in a string) are separated from each other with '-' character.
a='some text'
b='some 0-376 text'
c='some text.0-376.some text again'
d='some text.0-376####.jpg'
Apparently I need to extract zero 0
and 376
in simple but reliable fashion. So the code works regardless where in a string the numbers are places: in the beginning, middle or the end. It should be delivering a constant result regardless what characters are around the number: letter, commas, periods, dollar or pound signs and etc.
Upvotes: 1
Views: 325
Reputation: 19641
You can achieve the desired using a regular expression:
import re
regex = re.compile('([0-9]+)-([0-9]+)')
match = regex.search('some text.0-376.some text again')
if match:
numbers = [int(s) for s in match.groups()]
# numbers -> [0, 376]
Upvotes: 1
Reputation: 168726
This sounds like a job for regular expressions:
import re
a='some text'
b='some 0-376 text'
c='some text.0-376.some text again'
d='some text.0-376####.jpg'
for text in a, b, c, d:
match = re.search(r'(\d+)-(\d+)', text)
if match:
left, right = map(int, match.groups())
print left, right
Upvotes: 2