String python查找字符串中的最大整数
编写函数largestNumbertext,该函数接受一个文本字符串并返回该文本中出现的最大int值,如果没有出现这样的值,则返回None 例如:String python查找字符串中的最大整数,string,python-2.7,String,Python 2.7,编写函数largestNumbertext,该函数接受一个文本字符串并返回该文本中出现的最大int值,如果没有出现这样的值,则返回None 例如: largestNumber("I saw 3 dogs, 17 cats, and 14 cows!") 返回int值17,而不是字符串17 及 返回None值None,而不是字符串None 我尝试使用isdigit函数来分离整数,但如何比较字符串?您可以尝试使用正则表达式,然后使用max和map函数: result = [e for e in r
largestNumber("I saw 3 dogs, 17 cats, and 14 cows!")
返回int值17,而不是字符串17
及
返回None值None,而不是字符串None
我尝试使用isdigit函数来分离整数,但如何比较字符串?您可以尝试使用正则表达式,然后使用max和map函数:
result = [e for e in re.split("[^0-9]", "I saw 3 dogs, 17 cats, and 14 cows!") if e != '']
# list 'result' elements are strings: ['3', '17', '14'], so we use map(int, list) to get integers
print max(map(int, result))
另一个解决方案是:
def findLargestNumber(text):
ls = list()
for w in text.split():
try:
ls.append(int(w))
except:
pass
try:
return max(ls)
except:
return None
print findLargestNumber('I saw 3 dogs, 17 cats, and 14 cows!')
print findLargestNumber('I saw ')
输出:
17
None
\d+用于查找长度大于1的十进制数或数字,如果生成,则会将其追加到数组nums中,最后是nums的最大值。您也可以这样做
def largestNumber(in_str):
l=[int(x) for x in in_str.split() if x.isdigit()]
return max(l) if l else None
首先,使用split在_str中基于空格进行拆分,以获得一个列表
此列表中的“数字”使用isdigit标识,并使用int转换为整数
这些数字作为列表存储在l中
表情
max(l) if l else None
如果l不为空,则在l中给出最大值,否则为无
给予
及
给予
以下内容对我很有用,而且效果很好! 递增字符串中的数字,然后打印出字符串中的最大数字 进口稀土 增加字符串中的数字 请记住,索引5是数字的起始位置,您可能需要根据字符串长度对其进行调整
您可以尝试创建两个变量,以查看max方法是否正常工作重复已删除的问题
import re
def extractmax(str1):
nums=re.findall("\d+",str1)
return max(nums)
def largestNumber(in_str):
l=[int(x) for x in in_str.split() if x.isdigit()]
return max(l) if l else None
max(l) if l else None
print(largestNumber("I saw 3 dogs, 17 cats, and 14 cows!"))
17
print(largestNumber("One person ate two hot dogs!"))
None
import re
name = "name 1"
number = re.search(r'\d+', str(name))
if number:
rx = r'(?<!\d){}(?!\d)'.format(number.group())
prefix = re.sub(rx, lambda x: str(int(x.group()) + 1), name)
print(prefix)
li = [int(prefix[5:])]
print("Largest name", max(li))