标签:改进 位置 bre 匹配 character 控制 har 字符 strong
看这个例子:
1 river = "Mississippi" 2 target = input("Input a character to find:") 3 for index in range(len(river)): 4 if target == river[index]: #如果匹配,则显示索引值,跳出循环 5 print("Letter found at index:",index) 6 break 7 else: #如果在循环正常结束时,还找不到匹配的,则显示失败信息 8 print("Letter",target,"not found in",river)
1 >>> river = "Mississippi" 2 >>> for value in enumerate(river): 3 print(value) 4 5 (0, ‘M‘) 6 (1, ‘i‘) 7 (2, ‘s‘) 8 (3, ‘s‘) 9 (4, ‘i‘) 10 (5, ‘s‘) 11 (6, ‘s‘) 12 (7, ‘i‘) 13 (8, ‘p‘) 14 (9, ‘p‘) 15 (10, ‘i‘)
由于这两个值是在每次循环时产生的,因此这两个值放在同一个元组(成组出现的值里)
改进后的代码是:
1 river = "Mississippi" 2 target = input("Input a character to find:") 3 for index,letter in enumerate(river): 4 if target == letter: #如果匹配,则显示索引值,跳出循环 5 print("Letter found at index:",index) 6 break 7 else: #如果在循环正常结束时,还找不到匹配的,则显示失败信息 8 print("Letter",target,"not found in",river)
2.如果要列出一个字母出现的所有位置,怎么办?试试删掉break语句,结果如下:
1 Input a character to find:s 2 Letter found at index: 2 3 Letter found at index: 3 4 Letter found at index: 5 5 Letter found at index: 6 6 Letter s not found in Mississippi
代码不完全正确,虽然找出了所有s,但还是显示了失败信息,没有break语句,意味着总是进入else子句,所以还要再改一下:
1 river = "Mississippi" 2 found = 0 3 target = input("Input a character to find:") 4 for index,letter in enumerate(river): 5 if target == letter: #如果匹配,则显示索引值,跳出循环 6 print("Letter found at index:",index) 7 #break 8 found += 1 9 else: #如果在循环正常结束时,还找不到匹配的,则显示失败信息 10 if not found: 11 print("Letter",target,"not found in",river)
运行结果:
1 Input a character to find:s 2 Letter found at index: 2 3 Letter found at index: 3 4 Letter found at index: 5 5 Letter found at index: 6
标签:改进 位置 bre 匹配 character 控制 har 字符 strong
原文地址:https://www.cnblogs.com/striving123/p/9120903.html