Letter at a Time¶
Did you know that using a for loop, you can examine a string one letter at a time? You can use range
and tell it how long the string is.
len()
returns anint
representing the total number of characters in the String (including punctuation and whitespace). For example, if the variablestr
contains the String"hello"
, thenlen(str)
will return5
.You can access single characters in the string by using square-bracket notation.
my_string[n]
returns then
th character in the String. The character positions are zero-based. If the variablemy_string
contains the String"ligature"
, thenmy_string[0]
(my_string
at index0
) will return'l'
, andmy_string[4]
(my_string
at index4
) will return't'
.
What You Should See¶
What is your message? Are you ready for this?
Your message is 23 characters long.
The first character is at index 0 and is 'A'.
The last character is at index 22 and is '?'.
Here are all the characters, one at a time:
0 - 'A'
1 - 'r'
2 - 'e'
3 - ' '
4 - 'y'
5 - 'o'
6 - 'u'
7 - ' '
8 - 'r'
9 - 'e'
10 - 'a'
11 - 'd'
12 - 'y'
13 - ' '
14 - 'f'
15 - 'o'
16 - 'r'
17 - ' '
18 - 't'
19 - 'h'
20 - 'i'
21 - 's'
22 - '?'
Your message contains the letter 'a' 2 times.
What You Should Do on Your Own¶
Assignments turned in without these things will receive half credit or less.
If you print
range(7)
, what do you see? What happens if you convert the range to a list and then print that out? E.g.,list(range(7))
The
for
loop is defined so that the loop variablei
iterates through the entire range objectrange(len(message))
. If themessage
was"Hello"
what number would be sent to the range function? What numbers would be included within that range object? List them out.If a string variable contains the value
"box"
, what is its length? What is the index (position) of the last character (the'x'
)?Currently the code prints out the number of ‘a’s in the message. Change it so that it instead prints out the number of vowels (
a A e E i I o O u U
).
©2021 Daniel Gallo
This assignment is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License.
Adapted for Python from Graham Mitchell’s Programming By Doing