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

letters_2_thru_4 = phrase[1:4]
#M[ont]y Python

letter_5_to_end = phrase[4:]
#Mont[y Python]

last_3_letters = phrase[-3:]
#Monty Pyt[hon]

first_3_letters = phrase[:3]
#[Mon]ty Python

three_letters_before_last = phrase[-4:-1]
#Monty Py[tho]n

copy_of_string = phrase[:]
#[Monty Python]

The expected output for each print statement is shown in square brackets in the preceding comment.

Related Video

Author: Nat Dunn

Nat Dunn is the founder of Webucator (, a company that has provided training for tens of thousands of students from thousands of organizations. Nat started the company 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.

Follow Nat on Twitter at @natdunn and Webucator at @webucator.

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.