0
0
PythonHow-ToBeginner · 3 min read

How to Access Characters of String in Python: Simple Guide

In Python, you can access characters of a string using indexing with square brackets, like string[index]. Indexing starts at 0 for the first character, and you can also use negative indexes to count from the end.
📐

Syntax

To get a single character from a string, use string[index]. The index is an integer where 0 is the first character. Negative indexes start from the end, with -1 as the last character.

Example parts:

  • string: your text
  • [index]: position of the character
python
character = string[index]
💻

Example

This example shows how to get the first, last, and a middle character from a string using indexing.

python
text = "hello"
first_char = text[0]
last_char = text[-1]
middle_char = text[2]
print(f"First: {first_char}")
print(f"Last: {last_char}")
print(f"Middle: {middle_char}")
Output
First: h Last: o Middle: l
⚠️

Common Pitfalls

Trying to access an index outside the string length causes an IndexError. Remember indexes start at 0, so the last index is len(string) - 1. Also, strings are immutable, so you cannot change characters by assignment.

python
text = "abc"
# Wrong: causes error
# print(text[3])

# Right: access last character
print(text[2])

# Wrong: trying to change character
# text[0] = 'z'  # This will cause an error
Output
c
📊

Quick Reference

OperationSyntaxDescription
Get first characterstring[0]Returns the first character
Get last characterstring[-1]Returns the last character
Get character at position 3string[3]Returns the 4th character (index starts at 0)
Get substringstring[start:end]Returns characters from start to end-1
Length of stringlen(string)Returns number of characters

Key Takeaways

Use square brackets with an index to access characters in a string.
Indexing starts at 0 for the first character and supports negative indexes from the end.
Accessing an index outside the string length causes an error.
Strings cannot be changed by assigning to an index because they are immutable.
Use slicing to get multiple characters or substrings.