Checkpoint 8.5.1.
- 11
- The blank space counts as a character.
- 12
- Yes, there are 12 characters in the string.
What is printed by the following statements?
s = "python rocks"
print(len(s))
len
function, when applied to a string, returns the number of characters in a string.IndexError: string index out of range
. The reason is that there is no letter at index position 6 in "Banana"
. Since we started counting at zero, the six indexes are numbered 0 to 5. To get the last character, we have to subtract 1 from the length. Give it a try in the example above.lastch = fruit[len(fruit)-1]
fruit[-1]
would be a more appropriate way to access the last index in a list.len
function to access other predictable indices, like the middle character of a string.fruit = "grape"
midchar = fruit[len(fruit)//2]
# the value of midchar is "a"
len
returns the length of a list (the number of items in the list). However, since lists can have items which are themselves sequences (e.g., strings), it important to note that len
only returns the top-most length.alist[0]
is the string "hello"
, which has length 5.s = "python rocks"
print(len(s))
alist = [3, 67, "cat", 3.14, False]
print(len(alist))
lst
to the variable output
.