某公司的笔试题——一个字符串中取最长数字的长度(包含小数点)

import re
f= open(r'C:\Users\Administrator\Desktop\a.txt','r') #1213121iygyuit3iu1y2ui1yh3uj1hb4j1h2uhykl,2l.1,21l,3.1,2.12,1...1.2.12222222221.431451253252...qwq1213wqw12131qwq#@
s= f.read()
s = re.sub(r'[a-zA-z]',' ',s)
s = re.sub(r'[#!$!@,`]',' ',s) # 先把字符串中除数字和小数点之外的字符去掉,此时s为‘1213121       3  1 2  1  3  1  4 1 2     2 .1 21  3.1 2.12 1...1.2.12222222221.431451253252...   1213   12131  ’
List = s.split() #以空格为界,把数字存入数组中
List = [i.strip('.') for i in List] #去掉首尾的.(数字中.不在首尾位置)
List = [i.split('.') for i in List] #以.把数组中的数字切开,此时List为 [['1213121'], ['3'], ['1'], ['2'], ['1'], ['3'], ['1'], ['4'], ['1'], ['2'], ['2'], ['1'], ['21'], ['3', '1'], ['2', '12'], ['1', '', '', '1', '2', '12222222221', '431451253252'], ['1213'], ['12131']]
max = 0
for i in List: 
    if len(i) < 2: #如果数字不包含小数,则此数组无子数组,之间比较长度
        if len(i[0]) > max:
            max = len(i[0])
    else:
        for j in range(len(i)-1):
            s2 = i[j] +'.'+ i[j + 1] # 如果数字包含小数点,把数组前后通过小数点拼起来
            s2 = s2.strip(' .')  # 去掉首尾小数点,防止出现‘’+.+111111111111111133333的情况
            if len(s2)> max: # 和max比较
                print(s2)
                max = len(s2)
print(max)

猜你喜欢

转载自www.cnblogs.com/yingyingdeyueer/p/12045747.html