Let the user input be 0207a97, using re 207 is extracted from list instead of 0207
str = input()
l = [int(i) for i in re.findall('\d+',str) if '9' not in i]
if len(l)>0:
print(max(l))
Let the user input be 0207a97, using re 207 is extracted from list instead of 0207
str = input()
l = [int(i) for i in re.findall('\d+',str) if '9' not in i]
if len(l)>0:
print(max(l))
You may use
import re
s = "0207a97"
l = [(int(i), i) for i in re.findall('\d+',s) if '9' not in i]
if len(l)>0:
print(max(l, key=lambda x: x[0])[1]) # => 0207
See the Python demo. That is, get the list of tuples with the first item as the integer value and the second item as the matched string value, then get the max value comparing only the first items, and print Item 2 of the tuple found.
Or, you may still just get the re.findall(r'\d+', s)
resulting list and make use of the key
argument with max
. Set it to int
and the values in the list will be compared as integer numbers:
l = [i for i in re.findall('\d+',s) if '9' not in i]
if len(l)>0:
print(max(l, key=int))
See another Python demo. From the docs:
key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example,
key=str.lower
). The default value isNone
(compare the elements directly).
You can add leading zeroes once you are printing it on screen. You may read this for a better clarification: https://stackoverflow.com/a/13499182
If we'd be capturing non-nine starting digits in our strings, maybe this would simply return that:
import re
print(re.match("^([0-8]+)", "0207a97").group(1))
0207
import re
a='0207a97'
a1=re.findall('(\d+)',a)
a1[0] #output - 0207
a1[1] #output - 97
This will give you the output as a list. You can modify the list as you wish.