Not only can we select a single character from a string, we can select entire chunks of characters from a string. We can do this with the following syntax:
This is called slicing a string. When we slice a string we are creating a new string that starts at (and includes) the
first_index and ends at (but excludes) the
Let’s look at some examples of this. Recall our favorite fruit:
favorite_fruit = 'blueberry' print(favorite_fruit) # => 'blueberry'
The indices of this string are shown in the diagram below.
Let’s say we wanted a new string that contains the letters
eberr. We could slice
favorite_fruit as follows:
print(favorite_fruit[3:8]) # => 'eberr'
Notice how the character at the first index,
e, is INCLUDED, but the character at the last index,
y, is EXCLUDED. If you look for the indices 3 and 8 in the diagram, you can see how the
y is outside that range.
We can also have open-ended selections. If we remove the first index, the slice starts at the beginning of the string and if we remove the second index the slice continues to the end of the string.
print(favorite_fruit[:4]) # => 'blue' print (favorite_fruit[4:]) # => 'berry'
Again, notice how the
berry is excluded from the first example and included in the second example.
You’re a programmer working for Copeland’s Corporate Company. At this company, each employee’s user name is generated by taking the first five letters of their last name.
A new employee, Rodrigo Villanueva, is starting today and you need to create his account. His
last_name are stored as strings in script.py.
Create a variable
new_account by slicing the first five letters of his
Temporary passwords for new employees are also generated from their last names.
Create a variable called
temp_password by creating a slice out of the third through sixth letters of
last_name. Your string should have a total of 4 characters.