Finding numbers within certain string in Python

Viewed 120

I'm starting to learn Python and just now getting into regular expressions. I want to figure out what is the best way to search a string to find a number (which can be different lengths) that is always directly following a certain substring.

For example:

string = """ this is a very long string with 495834 other numbers;
             if I had the ( 5439583409 );
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ..."""

I want to be able to search the string for "Keyword_indicator" which only shows up here, then pull the number within the parenthesis, knowing the number isn't a set length.

output = "53029453"

Edit - The string has other numbers in it, and the number I'm looking for is always an integer.

4 Answers
import re
string = """ this is a very;
             long string if I had the;
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ..."""
m = re.search('Keyword_indicator.*?(\d+)', string)
output = m.group(1)

In your case you can use:

import re
string = """ this is a very long string with 495834 other numbers;
             if I had the ( 5439583409 );
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ..."""

#This would also match 5439583409 from bla5439583409bla.
re.findall(r'\d+', string)
result will be:
['495834', '5439583409', '53029453']

#If you only want numbers delimited by word boundaries (space, period, comma), you can use \b :
re.findall(r'\b\d+\b', string)
result will be:
['495834', '5439583409', '53029453']

#list of numbers instead of a list of strings:
[int(s) for s in re.findall(r'\b\d+\b', string)]

Here's one way of doing it:

string = 'biu89'
numbers = ''
for l in string:
    try: numbers+=str(int(l))
    except: pass
print(numbers)

Output:

89

note: All numbers will be concatenate to one.

Could could try something similar to the following:

>>> import re #import rejex
>>> just='Standard Price:20000' #provide a string
>>> re.search(r'\d+',just).group() #searches string for a digit values and groups
'20000' #result

So it would be something to the effect of:

string = """ this is a very;
             long string if I had the;
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ...""" #OP provided string
print(re.search(r'\d+', string).group()) #search for digit values in OP provided string, group, and output the result. 
Related