问题描述:
Your job is to write a function which increments a string, to create a new string.
- If the string already ends with a number, the number should be incremented by 1.
- If the string does not end with a number. the number 1 should be appended to the new string.
Examples:
foo -> foo1
foobar23 -> foobar24
foo0042 -> foo0043
foo9 -> foo10
foo099 -> foo100
Attention: If the number has leading zeros the amount of digits should be considered.
代码实现:
#codewars第十六题 (有错误)
def increment_string(strng):
if strng == '': return '1'
my_str = list(strng)
_length = len(strng)
num = 0
n = 0
for i in range(_length-1,-1,-1):
if ord(strng[i]) >= 48 and ord(strng[i]) <= 57: #是数字(48-57) 继续
if ord(strng[i]) == 48: #如果是0
num += 1
if (num == 1) or (strng[i+1] == '9'):
my_str.pop(i)
break
else:
num += int(strng[i])*pow(10,n)
n += 1
my_str.pop(i)
else:
num += 1
break
if n == _length: num += 1
_length0 = len(my_str)
ss = ''
for j in range(0,_length0):
ss = ss + my_str[j]
return ss+str(num)
#另解
def increment_string(strng):
head = strng.rstrip('0123456789') #删除 string 字符串末尾的指定字符(默认为空格). '0123456789' 就是删除在0123456789中的值 只要有就删除
tail = strng[len(head):] #从头的结尾处开始取到最后 就是把后面的数字串取出来
if tail=='':
return head+'1'
return head + str(int(tail)+1).zfill(len(tail)) #zfill方法返回指定长度的字符串(括号内为指定长度),原字符串右对齐,字符串长度不够,在字符串前面填充0。
increment_string("foo002")