Python comes with some built-in functions for working with strings. One of the most commonly used of these functions is
len() returns the number of characters in a string
favorite_fruit = "blueberry" length = len(favorite_fruit) print(length) # => 9
If you are taking the length of a sentence the spaces are counted as well.
fruit_sentence = "I love blueberries" print(len(fruit_sentence)) # => 18
len() comes in handy when we are trying to select characters from the end of a string. What is the index of the last character,
favorite_fruit from above? You can try to run the following code:
last_char = favorite_fruit[len(favorite_fruit)] print(last_char) # => IndexError
Why does this generate an
IndexError? Because the indices start at
0, so the final character in
favorite_fruit has an index of
9 and, because there is no value at that index, an
Instead, the last character in a string has an index that is
len(string_name) - 1.
last_char = favorite_fruit[len(favorite_fruit)-1] print(last_char) # => 'y'
You could also slice the last several characters of a string using
length = len(favorite_fruit) last_chars = favorite_fruit[length-4:] print(last_chars) # => 'erry'
len() statement as the starting index and omitting the final index lets you slice
n characters from the end of a string, where
n is the amount you subtract from
Copeland’s Corporate Company also wants to update how they generate temporary passwords for new employees.
Write a function called
password_generator that takes two inputs,
last_name and then concatenate the last three letters of each and returns them as a string.
Test your function on the provided
last_name and save it to the variable