|
发表于 2017-12-4 14:16:08
|
显示全部楼层
本帖最后由 shigure_takimi 于 2017-12-4 14:32 编辑
- def increment_string(string):
- if string[-1].isdigit():
- return string[:-1]+str(int(string[-1])+1)
- else:
- return string+'1'
- print(increment_string('This is an example!')) # ->This is an example!1
- print(increment_string('MSK是帅锅~6')) # ->MSK是帅锅~7
复制代码
## 题主出题有歧义。我还以为只看最后一位数字呢。
## 如果结尾是19,就会变成110,而看题主的意思应是变成20,
## 这样就要判断结尾连续有几位数字,我还没有学习正则表达式,要多写好几行代码。
- def countDigit(string):
- # 判断结尾连续有几位数字
- index = -1
- count = 0
- while string[index].isdigit():
- count += 1
- index -= 1
- return count
- def increment_string(string):
- count = countDigit(string) # 字符串结尾数字位数
- if count == 0:
- return string+'1'
- else:
- return string[:-count]+str(int(string[-count:])+1)
- print(increment_string('This is an example!')) # ->This is an example!1
- print(increment_string('MSK是帅锅~6')) # ->MSK是帅锅~7
- print(increment_string('MSK是帅锅~9999999')) # ->MSK是帅锅~10000000
复制代码 |
|