python找最长的字符串_在Python字符串中按数字顺序查找最长的字符串

I have a string with thousands of number in it. I need to go through the string and find the longest set of characters that are in numerical order. For example:

string = '1223123341223455'

The longest string of characters in that string in numerical order is 1223455 and it is 7 characters long. Here is an example of what I have at the moment:

r=r2=''

a=b=0

while a < len(string)+1:

if string[a] <= string[b]:

r += string[a]

else:

if len(r) < len(r2):

r = r2

a += 1

b += 1

With this it tells me that the string index is out of range on the line:

if string[a] <= string[b]

Here is my logic: Check to see if the first number is less than or equal to the second number. If it is, those two numbers are in numerical order. Add that first number to an empty string. Keep doing this until you run into a point when the first number is greater than the second number. After this point is reached, save what you have as a string and continue where you left off, except this time concatenate the number you accumulate to a different string. After you have two strings of numbers, compare the two and take the higher one. Continue this until you are done processing the string. I hope this makes sense, kind of hard to explain.

解决方案

Strings are indexed at 0. So if you try to access some_str[len(some_str)] you will get an IndexError because the highest index of that string is len(some_str) - 1. Change your while condition to: while a < len(myString):. Also, you shouldn't use string as a variable, as it may overshadow the python string module name.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值