• google plus

How to Slice Strings in Python

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:

  1. The slice begins with the character at first_pos and includes all the characters up to but not including the character at last_pos.
  2. If first_pos is left out, then it is assumed to be 0. So "hello"[:3] would return "hel".
  3. If last_pos is 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 "hello"[3:] would return "lo".

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.

Related Video

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for technical training with his business expertise and to help companies benefit from both. His previous experience was in sales, business and technical training, and management. Nat has an MBA from Harvard Business School and a BA in International Relations from Pomona College.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.