← Back to Tutorials Chapter 4

Strings

String Basics

Strings are sequences of Unicode characters. You can write them with single quotes, double quotes, or triple quotes for multiline strings:

single = 'Hello'
double = "World"
triple = """This spans
multiple lines"""
also_triple = '''This works too'''

Slicing

Slicing extracts a portion using [start:stop:step]:

text = "Python"
print(text[0:2])    # Py
print(text[:3])     # Pyt
print(text[2:])     # thon
print(text[::-1])   # nohtyP (reverse)
print(text[::2])    # Pto (every other)

Immutability

Strings are immutable — you cannot change a character in place:

s = "hello"
# s[0] = "H"  # TypeError!
s = "H" + s[1:]  # "Hello" — creates a new string

Concatenation and Repetition

full = "Hello" + " " + "World"  # "Hello World"
line = "-" * 20                  # "--------------------"
print("Hey" * 3)                 # HeyHeyHey

String Formatting

f-strings (Python 3.6+)

name = "Alice"
age = 30
print(f"{name} is {age} years old")
print(f"{name!r}")  # repr of name
print(f"{age:04d}") # "0030"

.format()

print("{} is {} years old".format("Bob", 25))
print("{1} is {0} years old".format(25, "Bob"))

% Operator (Legacy)

print("%s is %d years old" % ("Charlie", 35))

Escape Sequences

newline = "Line1\nLine2"     # newline
tabbed = "Col1\tCol2"         # tab
quote = "She said \"Hi\""     # double quote
backslash = "C:\\Users\\name" # backslash

Use raw strings with r"..." to ignore escape sequences:

path = r"C:\Users\name"  # no escaping needed

Common String Methods

text = "  Hello, World!  "

text.upper()          # "  HELLO, WORLD!  "
text.lower()          # "  hello, world!  "
text.strip()          # "Hello, World!"
text.split(",")       # ["  Hello", " World!  "]
",".join(["a","b","c"])  # "a,b,c"
text.replace("World", "Python")  # "  Hello, Python!  "
text.find("World")    # 8
text.count("l")       # 3
text.startswith("  He")  # True
text.endswith("!  ")  # True

Checking String Content

"hello".isalpha()    # True
"123".isdigit()      # True
"abc123".isalnum()   # True
"   ".isspace()      # True
"Hello".istitle()    # True
Python string operations
Note: f-strings are the recommended way to format strings in modern Python. They are faster and more readable than .format() and the % operator.

Practice Exercise

Write a program that asks the user for a sentence. Print the number of characters, words, and vowels in the sentence. Then reverse the sentence word-by-word (e.g. "Hello world" → "world Hello"). Finally, replace all vowels with * and print the result.