我有两个字符串,即'This is a test as146634546576 string 12312523'
和'This is a test as576 string 12344612523'
现在我要打印最大的数字,分别为146634546576
和12344612523
。我已经编写了以下代码,但仅打印146634546576
和576
。应该在12344612523
而不是576
的地方!
def findLargestNumber(text):
front = -1
li = []
li1 = []
for i in range(len(text)):
if front == -1:
if text[i].isdigit():
front = i
else:
continue
else:
if text[i].isdigit():
continue
else:
li.append(int(text[front:i+1]))
front = -1
return max(li)
#print max(li)
for w in text.split():
li1.append(int(w))
return max(li1)
#print max(li1)
if max(li)>max(li1):
return max(li)
else:
return max(li1)
print findLargestNumber('This is a test as146634546576 string 12312523')
print findLargestNumber('This is a test as576 string 12344612523')
答案 0 :(得分:0)
import re
a = 'This is a test as146634546576 string 12312523'
b = 'This is a test as576 string 12344612523'
num_in_a = re.findall(r'[\d]+', a)
num_in_b = re.findall(r'[\d]+', b)
print(max(map(int, num_in_a)))
print(max(map(int, num_in_b)))
输出:
146634546576
12344612523
答案 1 :(得分:0)
将max()
与re.findall
一起使用:
import re
a = 'This is a test as576 string 12344612523'
print(max(map(int, re.findall(r'\d+', a))))
# 12344612523
答案 2 :(得分:0)
import re
pa = re.compile(r'(\d+)')
def findLargestNumber(text):
ma = pa.findall(text)
num = [int(x) for x in ma]
print(max(num))
findLargestNumber('This is a test as576 string 12344612523')
findLargestNumber('This is a test as146634546576 string 12312523')