How are strings created in Python and what are the different string literal types?
Python provides several ways to create strings:
- Single quotes:
'hello' - Double quotes:
"hello"(functionally identical to single quotes) - Triple quotes:
'''multi-line'''or"""multi-line"""for multi-line strings and docstrings - Raw strings:
r'no\escape'-- backslashes treated literally - F-strings:
f'Hello, {name}'-- inline expressions (Python 3.6+) - Byte strings:
b'bytes'-- bytes, not text - str() constructor:
str(42)converts other types to string
Strings are immutable sequences of Unicode characters. You cannot modify a string in-place; all string methods return new strings.
Single: 'hello'
Double: "hello"
Triple: '''multi-line''' or """multi-line"""
Raw: r'C:\path\to\file' (no escape processing)
F-string: f'Hello, {name}' (expression interpolation)
Bytes: b'hello' (bytes, not str)
Constructor: str(42) -> '42'
# Single and double quotes are identical
s1 = 'hello'
s2 = "hello"
print(s1 == s2) # True
# Use one to contain the other
print("it's easy") # it's easy
print('He said "hi"') # He said "hi"
# Triple-quoted strings for multi-line
message = """This is
a multi-line
string."""
print(message)
# Raw strings -- backslashes are literal
path = r'C:\Users\alice\documents'
print(path) # C:\Users\alice\documents
# Without raw: need to escape
path2 = 'C:\\Users\\alice\\documents'
print(path == path2) # True
# F-strings (Python 3.6+)
name = "Alice"
age = 30
print(f"Hello, {name}! You are {age} years old.")
print(f"Next year: {age + 1}") # expressions
print(f"Name: {name!r}") # repr: 'Alice'
print(f"Pi: {3.14159:.2f}") # formatting: 3.14
print(f"{'hello':>20}") # right-align in 20 chars
# String constructor
print(str(42)) # '42'
print(str(3.14)) # '3.14'
print(str([1, 2])) # '[1, 2]'
print(str(True)) # 'True'
# Byte strings
b = b"hello"
print(type(b)) # <class 'bytes'>
print(b.decode('utf-8')) # 'hello' (bytes -> str)
# String immutability
s = "hello"
try:
s[0] = "H"
except TypeError as e:
print(f"Error: {e}") # 'str' object does not support item assignment
# Create modified string instead
s = "H" + s[1:]
print(s) # Hello
- •Single and double quotes are identical in Python
- •Triple quotes for multi-line strings and docstrings
- •Raw strings (r'...') treat backslashes as literal characters
- •F-strings allow inline expressions with formatting
- •Strings are immutable -- all methods return new strings
- •Raw strings cannot end with an odd number of backslashes: r'path\' is a SyntaxError
- •b'hello' is bytes, not str -- they are different types
- •Triple-quoted strings include leading newlines and indentation
- •f'{value}' calls str() on the value, f'{value!r}' calls repr()