How to Index Strings in Python

  • google plus

In Brief...

Indexing is the process of finding a specific element within a sequence of elements through the element's position. Remember that strings are basically sequences of characters. We can use indexing to find a specific character within the string.

Take our Introduction to Python Training course for free.

See the Course Outline and Register

Instructions

  • If we consider the string from left to right, the first character (the left-most) is at position 0.
  • If we consider the string from right to left, the first character (the right-most) is at position -1.

The table below illustrates this for the phrase "MONTY PYTHON".

Python Indexing

The following code shows how to find characters by position using indexing.

phrase = "Monty Python"

first_letter = phrase[0]
#[M]onty Python
print(first_letter)

last_letter = phrase[-1]
#Monty Pytho[n]
print(last_letter)

fifth_letter = phrase[4]
#Mont[y] Python
print(fifth_letter)

third_letter_from_end = phrase[-3]
#Monty Pyt[h]on
print(third_letter_from_end)

The expected output for each call to print() 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