3. Length
len() is a built-in function that returns how many characters a string has. Its signature is:
text— a string, or any other object that has a length.
Every character counts as one: letters, digits, spaces and punctuation. "Hello world" has 11 characters because the space between the words is also a character.
The length is useful together with indexing. The valid indexes of a string go from 0 to len(text) - 1, so text[len(text) - 1] is the same as text[-1]: the last character.
len() also works on lists; you used it in the lists chapter. With a string it counts characters, not words.
Coming from JavaScript? len(text) is text.length. It is a function, not a property, and it also works on lists, tuples, dicts and sets.
Length of a string
len() returns how many characters a string has.
Print the length of "Python".
Print exactly:
Create a free account to save your progress and unlock chapter 2.
The empty string
"" is a string with no characters.
Print the length of the empty string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Spaces are characters
Every character counts, including the space between two words.
Create a variable named phrase with the value "Hello world", then print its length.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Last index from the length
The valid indexes go from 0 to len(word) - 1.
Create a variable named word with the value "Python", then print its last character by indexing word with len(word) - 1.
Print exactly:
Create a free account to save your progress and unlock chapter 2.