- Using loops and comparisons, you can do some pretty nifty things with strings of characters
- Performing comparisons is much more powerful when you use loops to inspect each individual character
- Note the in operator works on strings as well as lists
#Declare a string
string = "John Henry was a desperate little man."
#Loop through each letter in the string, and print with a space after each
for letter in string:
print(letter)
#Quick length calculation
string_length = len(string)
print("String Length:",string_length)
#Set counters to 0
vowels = 0
others = 0
#Loop string and count vowels
for letter in string:
#if a vowel...
if letter in "aeiuo":
vowels += 1
#if not a vowel
else:
others += 1
#Print the total counts once complete
print("Vowels: ",vowels)
print("Others: ",others)
Tasks
- Type in the code and test it works
- Modify the program to count uppercase and lowercase letters
- Modify the program to count punctuation and spaces
- Save and label your code
Extension Task
The break command allows you to exit a for loop at any time. You can use this to modify your program to print an error and quit if a number is detected in the input string.