Interesting facts about strings in Python

Python strings have several fascinating characteristics that make them unique among programming languages. Let's explore four key features: immutability, escape sequence detection, direct slicing, and indexed access.

Immutability

Python strings are immutable, meaning once created, their content cannot be modified. You can only read from strings, not change individual characters ?

text = 'Tutorials Point'
print(text)

# This will raise an error
try:
    text[0] = 't'
except TypeError as e:
    print(f"Error: {e}")
Tutorials Point
Error: 'str' object does not support item assignment

To "modify" a string, you must create a new one ?

text = 'Tutorials Point'
new_text = 't' + text[1:]  # Create new string
print(new_text)
tutorials Point

Auto-detection of Escape Sequences

Python automatically recognizes and processes escape sequences like \n, \t, and \ within strings ?

text = 'Tutorials Point'
print(text + "\n" + "Python Tutorial")

# Other escape sequences
print("Tab\tSeparated\tText")
print("Quote: "Hello World"")
Tutorials Point
Python Tutorial
Tab	Separated	Text
Quote: "Hello World"

Direct Slicing

Python's slicing feature allows extracting substrings using the syntax [start:end:step]. The start index is included, end index is excluded, and step defaults to 1 ?

text = 'Tutorials Point'

print(text[0:5])    # First 5 characters
print(text[10:])    # From index 10 to end
print(text[:9])     # From start to index 9
print(text[::2])    # Every 2nd character
print(text[::-1])   # Reverse string
Tutor
Point
Tutorials
Ttras on
tnioP slairotuT

Indexed Access

Since strings store characters in contiguous memory, you can access any character directly using its index. Python supports both positive and negative indexing ?

text = 'Tutorials Point'

print(text[0] + text[1])    # First two characters
print(text[-1])             # Last character
print(text[-5:])            # Last 5 characters

# Check string length
print(f"Length: {len(text)}")
print(f"Character at index 9: {text[9]}")
Tu
t
Point
Length: 15
Character at index 9:  

Summary Table

Feature Description Example
Immutability Cannot modify after creation text[0] = 'x' raises error
Escape Sequences Automatic processing of \n, \t, etc. "line1\nline2"
Slicing Extract substrings with [start:end:step] text[0:5]
Indexing Direct character access by position text[0], text[-1]

Conclusion

These string features make Python powerful for text processing. Immutability ensures data integrity, slicing enables flexible substring extraction, and indexing provides efficient character access.

---
Updated on: 2026-03-25T06:17:18+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements