Tutorials Python Python Strings
Ch 8 / 58
Python Beginner 10 min read Chapter 8 of 58

Python Strings

Strings are one of Python's most-used data types — every piece of text, from a username to a webpage, lives in a string. This chapter covers creating strings, indexing, slicing, all built-in string methods, escape characters, multiline strings, and the modern f-string formatting syntax.

What you'll learn in this chapter
What strings are and how to create them
String indexing (positive & negative)
String slicing with step values
All essential built-in string methods
Escape characters & raw strings
String formatting & f-strings
Advertisement

What is a String?

A string in Python is a sequence of characters enclosed in quotes. Strings are used to store and manipulate text — names, sentences, file paths, URLs, and much more. In Python, strings are objects of the built-in str class.

Strings in Python are immutable — once created, individual characters cannot be changed. Every string operation returns a new string. Strings are also sequences, meaning they support indexing, slicing, and iteration just like lists.

Key fact In Python, single quotes 'hello' and double quotes "hello" are completely equivalent. Use triple quotes """...""" or '''...''' for multiline strings.
Sequence Type
Ordered, indexable characters
Immutable
Cannot change in-place
Unicode
Full Unicode support
50+ Methods
Rich built-in toolbox

Creating Strings

Python provides four ways to define string literals. All four styles are valid — choose based on your content and style needs.

Python — string_creation.py
# 1. Single quotes
name = 'Alice'

# 2. Double quotes
greeting = "Hello, World!"

# 3. Triple single quotes (multiline)
poem = '''Roses are red,
Violets are blue,
Python is awesome,
And so are you!'''

# 4. Triple double quotes (multiline / docstrings)
bio = """Name: Alice
Age: 25
City: Vadodara"""

# Type check
print(type(name))        # <class 'str'>
print(len(name))         # 5

# Strings with quotes inside
s1 = "It's a great day!"   # single inside double
s2 = 'He said "Hello!"'   # double inside single
s3 = "She said \"Python!\"" # escaped double quote

# Empty string
empty = ""
print(bool(empty))       # False — empty string is falsy
String concatenation & repetition Use + to join strings and * to repeat them: "Hello" + " " + "World" → "Hello World" and "ha" * 3 → "hahaha".
Python — string_ops.py
first = "Python"
last  = "Rocks"

# Concatenation
print(first + " " + last)  # Python Rocks

# Repetition
print("=" * 30)            # ==============================

# Membership test — 'in' operator
print("Py" in first)        # True
print("Java" not in first) # True

# Length
print(len(first))          # 6

# Iteration
for ch in "abc":
    print(ch, end="-")      # a-b-c-

String Indexing

Every character in a string has a position number called an index. Python uses zero-based indexing — the first character is at index 0. Python also supports negative indexing — -1 is the last character, -2 the second-to-last, and so on.

Index positions of the string "Python"
Positive index (left→right) Negative index (right→left)
0
1
2
3
4
5
P
y
t
h
o
n
-6
-5
-4
-3
-2
-1
Python — string_index.py
s = "Python"

# Positive indexing
print(s[0])    # P   — first character
print(s[1])    # y
print(s[5])    # n   — last character (len=6, so index 5)

# Negative indexing
print(s[-1])   # n   — last character
print(s[-2])   # o
print(s[-6])   # P   — first character

# Strings are immutable — this raises TypeError:
# s[0] = "J"  →  TypeError: 'str' object does not support item assignment

# To "change" a character, create a new string:
new_s = "J" + s[1:]
print(new_s)   # Jython
IndexError Accessing an index that doesn't exist raises an IndexError. For a string of length 6, valid positive indices are 0–5 and valid negative indices are -1 to -6.

String Slicing

Slicing extracts a portion (substring) of a string using the syntax s[start:stop:step]. The start index is inclusive, the stop index is exclusive, and step controls how many characters to skip. Any value can be omitted.

Python — string_slice.py
s = "Hello, Python!"
#    0123456789...

# Basic slicing [start:stop]
print(s[0:5])    # Hello    (index 0,1,2,3,4)
print(s[7:13])   # Python

# Omitting start or stop
print(s[:5])     # Hello    (start defaults to 0)
print(s[7:])     # Python!  (stop defaults to end)
print(s[:])      # Hello, Python!  (full copy)

# Step value
print(s[::2])    # Hlo yhn  (every 2nd char)
print(s[::-1])   # !nohtyP ,olleH  (reversed!)

# Negative indices in slicing
print(s[-7:-1])  # Python
print(s[-1:])    # !   (last character)

# Practical: reverse a string
word = "madam"
print(word == word[::-1])  # True — palindrome check!
Slice Result Explanation
s[1:4] "ell" Indices 1, 2, 3 (stop is exclusive)
s[:5] "Hello" From start up to (not including) index 5
s[7:] "Python!" From index 7 to end
s[::2] every 2nd char Step 2 — skip every other character
s[::-1] reversed string Step -1 — walk backwards
s[-7:-1] "Python" Negative indices with slice

Built-in String Methods

Python strings come with over 50 built-in methods. Because strings are immutable, every method returns a new string — the original is never modified. Here are the most important ones grouped by category.

Case Conversion

Python — case_methods.py
s = "hello, Python World!"

print(s.upper())        # HELLO, PYTHON WORLD!
print(s.lower())        # hello, python world!
print(s.title())        # Hello, Python World!
print(s.capitalize())   # Hello, python world!
print(s.swapcase())    # HELLO, pYTHON wORLD!

# Check case
print("HELLO".isupper())  # True
print("hello".islower())  # True
print("Hello World".istitle()) # True

Search & Replace

Python — search_replace.py

Split & Join

Python — split_join.py
sentence = "apple,banana,cherry,date"

# split() — splits into a list
fruits = sentence.split(",")
print(fruits)  # ['apple', 'banana', 'cherry', 'date']

# split with maxsplit
print(sentence.split(",", 2))
# ['apple', 'banana', 'cherry,date']

# splitlines() — split on newlines
multi = "line1\nline2\nline3"
print(multi.splitlines()) # ['line1', 'line2', 'line3']

# join() — joins a list into a string
print(" | ".join(fruits))
# apple | banana | cherry | date

print("-".join(["2024", "01", "15"]))
# 2024-01-15

Strip & Padding

Python — strip_pad.py
s = "   Hello, Python!   "

print(s.strip())    # "Hello, Python!"   — both sides
print(s.lstrip())   # "Hello, Python!   " — left only
print(s.rstrip())   # "   Hello, Python!" — right only

# Strip specific characters
print("***Python***".strip("*"))  # Python

# Padding / alignment
word = "Hi"
print(word.ljust(10))         # "Hi        "  left-align in 10 chars
print(word.rjust(10))         # "        Hi"  right-align
print(word.center(10))        # "    Hi    "  center
print(word.center(10, "*"))   # "****Hi****"  fill char
print("42".zfill(5))           # "00042"  — zero-pad

Complete Method Reference

Method Description Example
upper() Convert to uppercase "hi".upper() → "HI"
lower() Convert to lowercase "HI".lower() → "hi"
title() Title-case every word "hello world".title() → "Hello World"
strip() Remove leading/trailing whitespace " hi ".strip() → "hi"
replace(old, new) Replace occurrences "abc".replace("b","x") → "axc"
split(sep) Split into list "a,b".split(",") → ["a","b"]
join(iterable) Join list into string "-".join(["a","b"]) → "a-b"
find(sub) Find index of substring (-1 if absent) "python".find("th") → 2
count(sub) Count non-overlapping occurrences "aaa".count("a") → 3
startswith(s) Check if string starts with s "Hello".startswith("He") → True
endswith(s) Check if string ends with s "Hello".endswith("lo") → True
isalpha() True if all characters are letters "abc".isalpha() → True
isdigit() True if all characters are digits "123".isdigit() → True
isalnum() True if all alphanumeric "abc123".isalnum() → True
isspace() True if all whitespace " ".isspace() → True

Escape Characters & Raw Strings

Escape sequences let you include special characters in strings using a backslash \. Raw strings (prefix r) treat backslashes literally — essential for file paths and regular expressions.

Python — escape_chars.py
# Common escape sequences
print("Hello\nWorld")    # \n — newline
print("Name:\tAlice")   # \t — horizontal tab
print("She said \"Hi!\"") # \" — escaped quote
print('It\'s fine')     # \' — escaped apostrophe
print("Back\\slash")    # \\ — literal backslash
print("\u0041 \u03B1")  # Unicode: A α

# \r — carriage return (overwrites from start)
print("Hello\rWorld")   # World (in most terminals)

# Raw strings — backslashes are literal
path = r"C:\Users\Alice\Documents"
print(path)              # C:\Users\Alice\Documents

regex = r"\d{3}-\d{4}"  # raw string for regex pattern
print(regex)             # \d{3}-\d{4}
Escape Meaning Output
\n Newline Moves to next line
\t Horizontal tab Adds a tab space
\\ Backslash Prints \
\' Single quote Prints '
\" Double quote Prints "
\r Carriage return Returns cursor to start of line
\0 Null character ASCII null byte
\uXXXX Unicode character Any Unicode code point

String Formatting & F-Strings

Python has evolved through three generations of string formatting. F-strings (Python 3.6+) are the modern standard — concise, readable, and the fastest option. Always prefer f-strings in new code.

Python — all three formatting styles
name = "Alice"
age  = 25
pi   = 3.14159

# 1. % operator (old style — avoid in new code)
print("Hello, %s! You are %d years old." % (name, age))

# 2. str.format() (Python 2.6+ — common in older code)
print("Hello, {}! You are {} years old.".format(name, age))
print("Pi = {:.2f}".format(pi))     # Pi = 3.14

# 3. f-strings (Python 3.6+ — RECOMMENDED)
print(f"Hello, {name}! You are {age} years old.")
print(f"Pi = {pi:.2f}")           # Pi = 3.14
print(f"Next year: {age + 1}")    # expressions inside {}
print(f"{name.upper()!r}")       # repr: 'ALICE'

F-String Format Specifiers

Python — f_string_formats.py
price  = 1234567.89
ratio  = 0.8765
value  = 255

# Number formatting
print(f"{price:,.2f}")    # 1,234,567.89  — thousands separator
print(f"{ratio:.1%}")     # 87.6%          — percentage
print(f"{value:08b}")    # 11111111       — binary, zero-padded 8 wide
print(f"{value:x}")      # ff             — hexadecimal
print(f"{value:o}")      # 377            — octal
print(f"{price:e}")      # 1.234568e+06   — scientific notation

# Alignment (width = 15)
print(f"{'Left':<15}")   # "Left           "
print(f"{'Right':>15}")  # "          Right"
print(f"{'Mid':^15}")    # "      Mid      "
print(f"{'Fill':*^15}")  # "******Fill*****"

# Python 3.8+ self-documenting expressions
x = 42
print(f"{x = }")         # x = 42  (great for debugging!)
f"…{expr}…"
F-strings evaluate any Python expression inside {} at runtime — variables, arithmetic, method calls, conditionals.
:.2f
Format specifier for 2 decimal places. Syntax: :[fill][align][width][,][.precision][type].
:,
Comma as thousands separator: f"{1000000:,}" → 1,000,000.
:.1%
Multiply by 100, add % sign, 1 decimal: f"{0.75:.1%}" → 75.0%.

Practice Python Strings Online — Free Compilers

Try all the string examples from this chapter directly in your browser. No installation needed — pick any of the free online Python environments below.

▶
Online Python 3 Compiler
Write, run and debug Python string code in your browser. Supports full Python 3 standard library.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • A string is an immutable sequence of Unicode characters. Use single, double, or triple quotes to create them.
  • Indexing starts at 0. Negative indices count from the end: -1 is the last character.
  • Slicing syntax is s[start:stop:step]. Step -1 reverses the string.
  • Key methods: upper(), lower(), strip(), replace(), split(), join(), find(), count().
  • Use raw strings (r"...") for file paths and regex to avoid accidental escape sequences.
  • F-strings (f"…{expr}…") are the modern, fastest way to embed values and format output.
📄
Free Resource
Download our Python Strings Cheat Sheet
Indexing, slicing, all string methods, escape chars & f-string formats — all on one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Immutable means that once a string object is created in memory, its characters cannot be changed in-place. If you write s = "hello" and then s = s.upper(), Python does not modify the original "hello" object — it creates a brand new string "HELLO" and points the variable s at it. The original "hello" object is eventually garbage-collected. This design makes strings safe to use as dictionary keys and ensures thread safety.

✓ Answer

Both find() and index() search for a substring and return the index of the first match. The key difference is in how they handle a missing substring. find() returns -1 when the substring is not found, making it safe for conditional checks. index() raises a ValueError exception when the substring is absent, which is useful when you expect it to be present and want a hard error if it isn't.

✓ Answer

The most Pythonic way is slice with step -1: s[::-1]. This creates a new string with all characters in reverse order. A second method is using reversed() with join(): "".join(reversed(s)). Both produce the same result. The slice method is preferred for its brevity. A common use case: palindrome check — s == s[::-1] returns True for words like "madam".

✓ Answer

Raw strings treat every backslash as a literal character — no escape sequence processing occurs. You should use them in two main situations: (1) Windows file paths — writing r"C:\Users\Alice\new_folder" avoids \n being interpreted as a newline and \U as a Unicode escape. (2) Regular expressions — regex patterns use backslashes heavily (e.g. r"\d+" for "one or more digits"). Using raw strings keeps regex patterns readable and avoids double-escaping ("\\d+").

✓ Answer

F-strings (formatted string literals, introduced in Python 3.6) embed expressions directly inside string literals using curly braces: f"Hello, {name}!". The main advantages over .format() are: (1) Simpler syntax — variables and expressions go inline rather than at the end, (2) Faster — f-strings are evaluated at parse time and benchmarked roughly 35–40% faster than .format(), and (3) More powerful — you can embed full Python expressions, format specifiers, and in Python 3.8+ use {x=} for debug output. F-strings are the recommended approach in all modern Python code.

MCQ 1 of 3
What is the output of "Python"[-1]?
MCQ 2 of 3
What does "Hello, World!"[::-1] return?
MCQ 3 of 3
Which of the following correctly uses an f-string to display a float to 2 decimal places?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel