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 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.
'hello' and double quotes "hello" are completely equivalent. Use triple quotes """...""" or '''...''' for multiline
strings.
Creating Strings
Python provides four ways to define string literals. All four styles are valid — choose based on your content and style needs.
# 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
+ to join strings and * to repeat
them: "Hello" + " " + "World" → "Hello World" and "ha" * 3 → "hahaha".
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.
"Python"
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. 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.
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
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
s = "the quick brown fox jumps over the lazy dog"
# find() — returns index, -1 if not found
print(s.find("fox")) # 16
print(s.find("cat")) # -1
# index() — same but raises ValueError if not found
print(s.index("fox")) # 16
# rfind() — find from right
print(s.rfind("the")) # 31
# count() — number of non-overlapping occurrences
print(s.count("the")) # 2
# replace(old, new, count=optional)
print(s.replace("fox", "cat")) # ...brown cat jumps...
print(s.replace("the", "a", 1)) # replace only 1st "the"
# startswith() / endswith()
print(s.startswith("the")) # True
print(s.endswith("dog")) # True
Split & Join
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
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.
# 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.
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
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!)
{} at runtime — variables, arithmetic, method calls, conditionals.:[fill][align][width][,][.precision][type].f"{1000000:,}" → 1,000,000.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.
- 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:-1is the last character. - Slicing syntax is
s[start:stop:step]. Step-1reverses 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.
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.
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.
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".
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+").
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.
"Python"[-1]?"Hello, World!"[::-1] return?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.