Python Strings β Complete Guide with Examples
In this tutorial, you'll learn everything about Python strings β from basic string operations to advanced formatting and Unicode handling. You'll use these skills in real applications like processing user input, Parsing files, and generating reports.
What You'll Learn
- Creating strings with quotes, triple-quotes, and str()
- String concatenation, repetition, and slicing
- String methods: split(), join(), strip(), replace(), find()
- String formatting: f-strings, .format(), %-formatting
- Unicode and encoding in Python 3
- Regular expression basics for string matching
Why Strings Matter
Every program works with text. User input, file contents, API responses, database records β they're all strings. Python's string handling is one of its strongest features. Security tools at DodaTech Process thousands of log entries per second, parsing strings to detect threats.
Creating Strings
A string is a sequence of characters enclosed in quotes:
# Single quotes
name = 'Alice'
# Double quotes (same thing)
greeting = "Hello, World!"
# Triple quotes for multi-line strings
poem = """Roses are red,
Violets are blue,
Python is fun,
And so are you."""
# str() converts other types to strings
number = str(42) # "42"
pi = str(3.14159) # "3.14159"
truth = str(True) # "True"
Expected output: None β these are variable assignments. Use print() to see them.
String Methods
Python strings have dozens of built-in methods. Here are the most useful ones:
text = " Hello, Python World! "
# Cleaning
print(text.strip()) # "Hello, Python World!"
print(text.lstrip()) # "Hello, Python World! "
print(text.rstrip()) # " Hello, Python World!"
# Case manipulation
print(text.upper()) # " HELLO, PYTHON WORLD! "
print(text.lower()) # " hello, python world! "
print(text.title()) # " Hello, Python World! "
print(text.swapcase()) # " hELLO, pYTHON wORLD! "
# Searching
print(text.find("Python")) # 9 (index where "Python" starts)
print(text.find("Java")) # -1 (not found)
print(text.count("o")) # 3
# Replacement
print(text.replace("Python", "JavaScript"))
# " Hello, JavaScript World! "
Expected output:
Hello, Python World!
Hello, Python World!
Hello, Python World!
HELLO, PYTHON WORLD!
hello, python world!
Hello, Python World!
hELLO, pYTHON wORLD!
9
-1
3
Hello, JavaScript World!
Splitting and Joining
These are critical for data processing:
csv_line = "Alice,30,Engineer,New York"
fields = csv_line.split(",")
print(fields) # ['Alice', '30', 'Engineer', 'New York']
# Join back with a different separator
print(" | ".join(fields)) # Alice | 30 | Engineer | New York
# Split on whitespace (default)
words = "Python is awesome".split()
print(words) # ['Python', 'is', 'awesome']
# Split into lines
multi = "Line1\nLine2\nLine3"
print(multi.splitlines()) # ['Line1', 'Line2', 'Line3']
String Formatting with f-Strings (Python 3.6+)
f-strings are the modern way to format strings. They're readable and fast:
name = "Alice"
age = 30
score = 95.5678
# Basic
print(f"Name: {name}, Age: {age}")
# Format specifiers
print(f"Score: {score:.1f}") # "Score: 95.6" (1 decimal place)
print(f"Score: {score:.0f}") # "Score: 96" (rounded to integer)
print(f"Percent: {score/100:.1%}") # "Percent: 95.6%"
# Padding and alignment
print(f"|{name:<10}|") # left-aligned: |Alice |
print(f"|{name:>10}|") # right-aligned: | Alice|
print(f"|{name:^10}|") # centered: | Alice |
# Expressions inside f-strings
print(f"Double score: {score * 2}")
print(f"Grade: {'Pass' if score >= 60 else 'Fail'}")
Expected output:
Name: Alice, Age: 30
Score: 95.6
Score: 96
Percent: 95.6%
|Alice |
| Alice|
| Alice |
Double score: 191.1356
Grade: Pass
Unicode and Encoding
Python 3 strings are Unicode by default. This matters when processing international text or reading files from different systems:
# Unicode characters
print("Hello, δΈη!") # Chinese characters
print("CafΓ©") # Accented characters
print("\u2603") # Unicode snowman: β
print("\U0001F600") # Emoji: π
# Encoding to bytes
text = "Python"
bytes_utf8 = text.encode("utf-8")
print(bytes_utf8) # b'Python'
print(type(bytes_utf8)) # <class 'bytes'>
# Decoding back to string
decoded = bytes_utf8.decode("utf-8")
print(decoded) # Python
# Common encoding issues
try:
# This fails because Β© isn't in latin-1... wait, it is!
text = "Python Β© 2026"
bytes_latin = text.encode("latin-1")
print(bytes_latin)
except UnicodeEncodeError as e:
print(f"Encoding error: {e}")
Expected output:
Hello, δΈη!
CafΓ©
β
π
b'Python'
<class 'bytes'>
Python
b'Python \xa9 2026'
Common Pitfalls
Pitfall 1: Strings are Immutable
name = "Hello"
name[0] = "J" # TypeError: 'str' object does not support item assignment
# Correct: create a new string
name = "J" + name[1:] # "Jello"
Pitfall 2: Comparing with is Instead of ==
a = "hello"
b = "".join(["h", "e", "l", "l", "o"])
print(a == b) # True (correct β compare value)
print(a is b) # False (compares identity, not value)
Pitfall 3: Forgetting strip() on User Input
user_input = " yes " # User typed with spaces
if user_input == "yes":
print("This won't print!")
if user_input.strip() == "yes":
print("This will print!")
Practice Questions
Write a function that takes a sentence and returns it with each word reversed (keep word order).
Given a list of names ["Alice", "Bob", "Charlie"], produce: "Alice, Bob, and Charlie" (Oxford comma).
Write a function that validates a password: at least 8 chars, one uppercase, one digit, one special character.
Extract all email addresses from a string like "Contact us at support@example.com or sales@test.org".
Write a function that converts snake_case to camelCase.
Challenge: Log Parser
Write a function that parses an Apache-style log line:
192.168.1.1 - - [29/Jun/2026:12:34:56 +0000] "GET /index.html HTTP/1.1" 200 2326
Extract and return the IP address, timestamp, HTTP method, path, status code, and bytes.
Real-World Task: Config File Reader
Write a function that reads a simple config file like:
# Database config
DB_HOST = localhost
DB_PORT = 5432
DB_NAME = myapp
# App settings
DEBUG = true
MAX_RETRIES = 3
Parse it into a dictionary, skipping comments and stripping whitespace. Handle both quoted and unquoted values. This is exactly how DodaTech tools read their configuration files to avoid hardcoding sensitive settings in source code.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro