0
0
Pythonprogramming~5 mins

String indexing (positive and negative) in Python

Choose your learning style9 modes available
Introduction

String indexing helps you pick out single letters from a word or sentence. You can count from the start or the end.

When you want to get the first letter of a name.
When you need the last character of a password to check it.
When you want to read a specific letter in a sentence.
When you want to reverse a string by using negative indexes.
When you want to slice parts of a string using positions.
Syntax
Python
string[index]

# index can be positive (start at 0) or negative (start at -1 from end)

Positive index starts at 0 for the first character.

Negative index starts at -1 for the last character.

Examples
Positive indexes: 0 is first letter, 4 is last letter in 'hello'.
Python
word = "hello"
print(word[0])  # prints 'h'
print(word[4])  # prints 'o'
Negative indexes: -1 is last letter, -5 is first letter in 'hello'.
Python
word = "hello"
print(word[-1])  # prints 'o'
print(word[-5])  # prints 'h'
Mixing positive and negative indexes to get letters from middle.
Python
sentence = "Python"
print(sentence[2])   # prints 't'
print(sentence[-3])  # prints 'h'
Sample Program

This program shows how to get letters from a word using positive and negative indexes.

Python
word = "friend"

first_letter = word[0]
last_letter = word[-1]
third_letter = word[2]
second_last_letter = word[-2]

print(f"First letter: {first_letter}")
print(f"Last letter: {last_letter}")
print(f"Third letter: {third_letter}")
print(f"Second last letter: {second_last_letter}")
OutputSuccess
Important Notes

Trying to use an index outside the string length will cause an error.

Strings are like a row of boxes, each box has one letter and a number (index).

Summary

Use positive indexes to count letters from the start (0, 1, 2...).

Use negative indexes to count letters from the end (-1, -2, -3...).

String indexing helps you pick any single letter easily.