[英]How to find the largest number of times a word is repeated consecutively in a given string?
[英]How can I find the largest number from the given string in Python?
我有两个字符串,即'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')
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
将max()
与re.findall
一起re.findall
:
import re
a = 'This is a test as576 string 12344612523'
print(max(map(int, re.findall(r'\d+', a))))
# 12344612523
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.