How to Slice Strings in Python

  • google plus

In Brief...

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]

Take our Introduction to Python Training course for free.

See the Course Outline and Register

Instructions

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

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, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.

Categories

Courses

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for web development with his business expertise and to help companies benefit from both.

Discuss