如何在Python中从给定的字符串中找到最大的数字?

时间:2018-10-13 05:47:46

标签: python python-3.x python-2.7

我有两个字符串,即'This is a test as146634546576 string 12312523''This is a test as576 string 12344612523'

现在我要打印最大的数字,分别为14663454657612344612523。我已经编写了以下代码,但仅打印146634546576576。应该在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')

3 个答案:

答案 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')