In our prior lesson on Python strings , we indicate looked at how to create a string and how to reference individual characters in string.
Now, we’ll look at how to excerpt multiple characters from a string. If you want to Python to talk about multiple letters, Python needs to know where to begin and where to end. So, you use indices as shown below. Look at the diagram below. The best way to figure this out is to run some code and explore a pattern:
1 2 3 4 5 6 7 8 |
str = "Penjee" print( str[0:1 ] ) print( str[0:2 ] ) print( str[0:3 ] ) print( str[1:1 ] ) print( str[1:2 ] ) print( str[1:3 ] ) print( str[1:4 ] ) |
The code above leads to the following console output:
Below is a closer look at the heart of this code, showing each index.
As you can see below, there are 2 integers , that represent the where you want to start and end. The trickiest part is that the second number is not inclusive.
What if we only enter 1 number and a colon ?
1 2 3 4 5 6 7 |
str = "Penjee" print( str[ 0: ] ) print( str[ 1: ] ) print( str[ 2: ] ) print( str[ 3: ] ) print( str[ 4: ] ) print( str[ 5: ] ) |
The code above leads to the console output below :
So, this is a handy shortcut when you know where you want to start in a string and you want to include all the characters through the end of the string.