python学习笔记 day05 习题讲解
输入一个字符串(由数字和字母组成,连续数字记为1,输出字符串中连续数字的个数)
s='ajjs235djk123jkasjak34aks12k1' #输出5 count=0 for i in range(len(s)): if i==0: if s[i].isdigit() and not s[i+1].isdigit(): count+=1 else: if i==len(s)-1: if s[i].isdigit(): count+=1 if s[i-1].isdigit() and not s[i].isdigit(): count+=1 print(count)
运行结果:
F:\workspace_python\pycharm_projects\venv\Scripts\python.exe F:/workspace_python/pycharm_projects/fullstack2018-08-17/week2/day07/01.py
5
另一种解法:
s=input('>>>') for i in s: #这里面的s还是原来输入的那个 if i.isalpha(): s=s.replace(i,' ') #这里虽然进行了替换,replace方法产生一个新的字符串对象又重新赋值给s L=s.split() print(L,len(L))
运行结果:
>>>jks12jskdk9283sjkdsjk223 ['12', '9283', '223'] 3
talk is cheap,show me the code