In Python, when you need to get a sequence of characters from a string (i.e., a substring), you get a slice of the string using the following syntax:
substring = original_string[first_pos:last_pos]
When slicing in Python, note that:
- The slice begins with the character at
first_posand includes all the characters up to but not including the character at
first_posis left out, then it is assumed to be 0. So
last_posis left out, then it is assumed to be the length of the string, or in other words, one more than the last position of the string. So
The following code shows how to get substrings using slicing.
phrase = "Monty Python" first_5_letters = phrase[0:5] #[Monty] Python print(first_5_letters) letters_2_thru_4 = phrase[1:4] #M[ont]y Python print(letters_2_thru_4) letter_5_to_end = phrase[4:] #Mont[y Python] print(letter_5_to_end) last_3_letters = phrase[-3:] #Monty Pyt[hon] print(last_3_letters) first_3_letters = phrase[:3] #[Mon]ty Python print(first_3_letters) three_letters_before_last = phrase[-4:-1] #Monty Py[tho]n print(three_letters_before_last) copy_of_string = phrase[:] #[Monty Python] print(copy_of_string)
The expected output for each print statement is shown in square brackets in the preceding comment.