Browse Python Topics ▼
Pick a Web Framework

Strings

📂 Strings & Text Processing 📘 Lesson 10 of 57

Master Python text processing through zero-based indexing, slicing formulas, negative offsets, immutability, escape characters, and raw strings.

In modern computing, text is everywhere. Whether you are building web applications, analyzing datasets, parsing system logs, or designing chatbots, processing textual information is a core responsibility of software engineering.

In Python, text is represented by the str (string) data type: an ordered, immutable sequence of Unicode characters.

Because Python supports Unicode natively, strings can represent any human language—English, Hindi, Mandarin, Arabic, Spanish—as well as mathematical symbols and emojis.


1. Creating Strings: Quotes and Escape Characters

You can define strings using single quotes (') or double quotes ("). Both behave identically:

single_quoted = 'Hello, Developer!'
double_quoted = "Hello, Developer!"

Choosing Single vs. Double Quotes

Use double quotes if your text contains an apostrophe, and single quotes if your text contains double quotation marks:

# Clean: no escape characters needed
message1 = "It's a fantastic day to write Python code."
message2 = 'She looked at the screen and shouted: "It works!"'

Escape Characters (\)

If you need to include quotes, newlines, or tabs inside a string, prefix the special character with a backslash (\):

Escape SequenceWhat It ProducesExample
\'Literal single quote'It\'s working'
\"Literal double quote"He said \"hello\""
\nNewline (line break)"First line\nSecond line"
\tTab indentation (4 spaces)"Column 1\tColumn 2"
\\Literal backslash"C:\\Users\\Alex"

Multi-Line Strings (Triple Quotes)

When you have a long paragraph or structured block of text spanning multiple lines, enclose it in triple quotes (""" or '''):

email_template = """Dear Customer,

Thank you for your recent purchase.
Your order has been confirmed and is now being packaged.

Best regards,
The Engineering Team"""

print(email_template)

Raw Strings (r"...")

When working with Windows file paths or regular expressions, backslashes are common. You can prefix a string with r (for raw) to tell Python to ignore all escape characters:

# Without 'r', \n is treated as a newline!
# With 'r', backslashes are treated as literal characters:
file_path = r"C:\new_projects\tasks.txt"
print(file_path)  # C:\new_projects\tasks.txt

2. String Indexing: Zero-Based and Negative Offsets

Because strings are ordered sequences, every character has a precise numerical position, called an index.

Python uses zero-based indexing: the very first character is at index 0, not 1:

String:      P    y    t    h    o    n
Positive:    0    1    2    3    4    5
Negative:   -6   -5   -4   -3   -2   -1
language = "Python"

# Positive indexing (from the front, starting at 0):
print(language[0])  # 'P'
print(language[1])  # 'y'
print(language[5])  # 'n'

Negative Indexing (From the Back)

One of Python’s most convenient features is negative indexing, which lets you count backward from the end of the string without needing to calculate its length:

# -1 always refers to the very last character:
print(language[-1])  # 'n'
print(language[-2])  # 'o'
print(language[-6])  # 'P'

The IndexError Trap

If you attempt to access an index that does not exist, Python will crash with an IndexError:

word = "Cat"  # Valid indexes: 0, 1, 2
print(word[5])
# IndexError: string index out of range

To find how many characters are in a string safely, use Python’s built-in len() function:

print(len("Python"))  # 6

3. String Slicing: Extracting Substrings

While indexing extracts a single character, slicing extracts an entire substring.

The complete slicing formula is:

$$\text{string}[\text{start} : \text{stop} : \text{step}]$$

  • start: The index where the slice begins (inclusive).
  • stop: The index where the slice ends (exclusive—stops right before this index).
  • step (optional): How many characters to skip forward (default is 1).
alphabet = "ABCDEFGHIJ"

# Slice from index 2 up to (but not including) index 6:
print(alphabet[2:6])  # "CDEF"

Omitting Start or Stop

If you leave start blank, Python defaults to the beginning (0). If you leave stop blank, Python slices all the way to the end:

phrase = "Hello World"

# From the beginning up to index 5:
print(phrase[:5])   # "Hello"

# From index 6 through to the very end:
print(phrase[6:])   # "World"

Using the Step Parameter

The step parameter controls the stride:

numbers = "0123456789"

# Take every second character:
print(numbers[::2])   # "02468"

# Take every third character:
print(numbers[::3])   # "0369"

The Legendary String Reversal Trick

If you pass a negative step of -1, Python walks backward from the end of the string to the beginning, reversing the string:

greeting = "stressed"
reversed_word = greeting[::-1]

print(reversed_word)  # "desserts"

Safety Advantage: Unlike indexing (text[100] crashes), slicing never raises an IndexError. If your slice bounds exceed the length of the string, Python gracefully stops at the boundary without crashing: alphabet[8:99] safely returns "IJ".


4. Immutability: Strings Cannot Be Modified

This is one of the most critical architectural concepts in computer science. In Python, strings are immutable. Once a string object is created in memory, its contents can never be changed or modified in place.

Attempting to change an individual character raises a TypeError:

name = "Jello"

# BROKEN CODE:
name[0] = "H"
# TypeError: 'str' object does not support item assignment

How to “Change” a String

To modify a string, you must create a new string by combining slices and assigning it:

name = "Jello"

# Create a brand new string combining "H" with the rest of the name:
name = "H" + name[1:]
print(name)  # "Hello"

Why Does Python Use Immutability?

  1. Performance & Memory (String Interning): Because strings cannot change, Python can safely reuse the same string object in memory across thousands of variables without fear of side effects.
  2. Security: Strings used as file paths, database URLs, and network sockets cannot be maliciously altered under the hood.
  3. Dictionary Keys: Only immutable objects can be hashed and used as reliable keys in dicts and sets.

5. String Operations

You can combine and manipulate strings using standard operators:

Concatenation (+)

Glues two strings together:

first = "Open"
last = "Roadmaps"
full = first + " " + last
print(full)  # "Open Roadmaps"

Repetition (*)

Repeats a string a given number of times:

# Great for printing clean terminal divider lines:
print("=" * 30)
print("       SYSTEM REPORT")
print("=" * 30)

Output:

==============================
       SYSTEM REPORT
==============================

Membership Testing (in and not in)

Checks whether a substring exists anywhere inside the string:

log_entry = "2026-10-15 [ERROR] Database connection timed out."

if "ERROR" in log_entry:
    print("Urgent: Incident detected in server logs!")

Summary Checklist

  • Quotes: Use '...' or "..." for single lines, and """...""" for multi-line paragraphs.
  • Raw Strings: Prefix with r"..." to ignore backslash escape codes in file paths.
  • Zero-Based: The first character is index 0; the last character is -1.
  • Slicing: [start:stop:step] extracts substrings (stop is exclusive).
  • Reversal: [::-1] quickly reverses any text.
  • Immutability: Strings can never be changed in place; operations create new strings.

Now that you understand string structure and slicing, continue to string-methods to learn how to search, strip, replace, split, and clean messy real-world text data.

Test your understanding of Strings

Quick interactive practice questions with instant feedback.

Take Quiz →