Chapter 4 - 4.5 Control and Strings PDF

Title Chapter 4 - 4.5 Control and Strings
Author Kyle Frudakis
Course Python Programming
Institution Florida Atlantic University
Pages 2
File Size 90.3 KB
File Type PDF
Total Downloads 91
Total Views 135

Summary

Dr. Oge Marques
Full Semester
Furthermore on how to manipulate string and string output...


Description

Chapter 4 - 4.5 Control and Strings Monday, May 24, 2021

6:04 PM

Manipulating string river = "Mississippi" • We can find the letter 'p' using the find method: river.find('p') output: 8 #find function implementations river = "mississippi" print(river.find('p')) for index in range(len(river)): print(index, end=" ") print() for index in range(len(river)): print(river[index], end='') 8 0 1 2 3 4 5 6 7 8 9 10 mississippi

#find function implementations river = "mississippi" target = input("input a character to find: ") for index in range(len(river)): if river[index] == target: print("Letter found at index: ", index) break else: print("Letter", target, "not found in", river) input a character to find: p Letter found at index: 8

• WE frequently look for both an index and the character ○ Python provides the enumerate iterator ○ provides both index and character itself for index, letter in enumerate(river): print(index, letter) 0m 1i 2s 3s 4i 5s 6s 7i 8p 9p

10 i • NOTICE: the for statement has two variables! ○ This is because the enumeration statement yields two values (outputs) ▪ index ▪ character • If the print statement were given one variable, output would have been in tuple form! • Knowing what we know about enumerators, lets edit our code #find function implementations river = "mississippi" target = input("input a character to find: ") for index, letter in enumerate(river): if letter == target: print("Letter found at index: ", index) break else: print("Letter", target, "not found in", river) input a character to find: p Letter found at index: 8 • If we want to print out all the instances of a letter, we can just get rid of the break statement • but then we get a problem with the fail else always showing even if we have successfully found them ○ This is how I fixed it #find function implementations river = "mississippi" count = 0 target = input("input a character to find: ") for index, letter in enumerate(river): count += 1 if letter == target: print("Letter found at index: ", index) if count == len(river): print("Letter", target, "not found in", river) input a character to find: j Letter j not found in mississippi...


Similar Free PDFs