Python Strings
Strings are one of the most commonly used data types in Python. A string is a sequence of characters enclosed in quotes. Python treats single and double quotes identically.
Creating Strings
python
# Single quotes
name = 'Alice'
# Double quotes
greeting = "Hello, World!"
# Triple quotes (multi-line)
paragraph = """This is a
multi-line string that
preserves line breaks."""
# Raw strings (ignore escape characters)
path = r"C:\Users\name\documents"
# Byte strings
data = b"binary data"String Indexing and Slicing
Strings are sequences, meaning each character has an index:
P y t h o n
0 1 2 3 4 5 (positive index)
-6 -5 -4 -3 -2 -1 (negative index)python
text = "Python"
# Indexing
print(text[0]) # P
print(text[3]) # h
print(text[-1]) # n
print(text[-3]) # h
# Slicing: [start:stop:step]
print(text[0:3]) # Pyt (characters 0, 1, 2)
print(text[2:5]) # tho
print(text[:3]) # Pyt (from beginning)
print(text[3:]) # hon (to end)
print(text[::2]) # Pto (every 2nd character)
print(text[::-1]) # nohtyP (reversed)
# Slicing with negative indices
print(text[-3:]) # hon
print(text[:-3]) # Pyt
print(text[-4:-1]) # thoString Immutability
Strings in Python are immutable β you cannot change individual characters:
python
text = "Hello"
# This will raise TypeError
# text[0] = "h" # TypeError: 'str' object does not support item assignment
# Instead, create a new string
text = "h" + text[1:]
print(text) # hello
# Or use replace()
text = "Hello"
text = text.replace("H", "h")
print(text) # helloString Methods
Case Methods
python
text = "Hello, World!"
print(text.upper()) # HELLO, WORLD!
print(text.lower()) # hello, world!
print(text.title()) # Hello, World!
print(text.capitalize()) # Hello, world!
print(text.swapcase()) # hELLO, wORLD!
print(text.casefold()) # hello, world! (aggressive lowercase)Search Methods
python
text = "Python is awesome and Python is popular"
print(text.find("Python")) # 0 (first occurrence index)
print(text.find("Python", 5)) # 23 (search from index 5)
print(text.find("Java")) # -1 (not found)
print(text.rfind("Python")) # 23 (last occurrence)
print(text.index("Python")) # 0 (like find, but raises ValueError if not found)
print(text.count("Python")) # 2
print(text.startswith("Python")) # True
print(text.endswith("popular")) # True
print("Python" in text) # TrueStrip and Pad Methods
python
text = " Hello, World! "
print(text.strip()) # "Hello, World!"
print(text.lstrip()) # "Hello, World! "
print(text.rstrip()) # " Hello, World!"
print(text.strip("! ")) # "Hello, World"
# Padding
num = "42"
print(num.zfill(5)) # "00042"
print(num.ljust(10, '-')) # "42--------"
print(num.rjust(10, '-')) # "--------42"
print(num.center(10, '-')) # "----42----"Split and Join
python
# Splitting
csv = "apple,banana,cherry,date"
fruits = csv.split(",")
print(fruits) # ['apple', 'banana', 'cherry', 'date']
text = "Hello World Python"
words = text.split() # Split on whitespace
print(words) # ['Hello', 'World', 'Python']
# Split with maxsplit
data = "name=John=Doe"
parts = data.split("=", 1)
print(parts) # ['name', 'John=Doe']
# Splitlines
multiline = "line1\nline2\nline3"
lines = multiline.splitlines()
print(lines) # ['line1', 'line2', 'line3']
# Joining
words = ['Python', 'is', 'great']
sentence = " ".join(words)
print(sentence) # "Python is great"
path = "/".join(["home", "user", "documents"])
print(path) # "home/user/documents"
csv_line = ",".join(["Alice", "30", "Engineer"])
print(csv_line) # "Alice,30,Engineer"Replace and Translate
python
text = "Hello World World"
# Replace
print(text.replace("World", "Python")) # Hello Python Python
print(text.replace("World", "Python", 1)) # Hello Python World
# Translate (character-level replacement)
table = str.maketrans("aeiou", "12345")
print("hello world".translate(table)) # h2ll4 w4rld
# Remove characters with translate
remove_digits = str.maketrans("", "", "0123456789")
print("abc123def456".translate(remove_digits)) # abcdefValidation Methods
python
print("hello".isalpha()) # True (only letters)
print("12345".isdigit()) # True (only digits)
print("hello123".isalnum()) # True (letters and digits)
print(" ".isspace()) # True (only whitespace)
print("Hello World".istitle()) # True (title case)
print("HELLO".isupper()) # True
print("hello".islower()) # True
print("abc123".isidentifier())# True (valid variable name)String Formatting
f-Strings (Python 3.6+, Recommended)
python
name = "Alice"
age = 30
score = 95.5678
# Basic interpolation
print(f"Name: {name}, Age: {age}")
# Expressions
print(f"In 5 years: {age + 5}")
print(f"Uppercase: {name.upper()}")
# Number formatting
print(f"Score: {score:.2f}") # 95.57 (2 decimal places)
print(f"Score: {score:10.2f}") # 95.57 (10 chars wide)
print(f"Percentage: {0.856:.1%}") # 85.6%
print(f"Big number: {1000000:,}") # 1,000,000
print(f"Binary: {42:b}") # 101010
print(f"Hex: {255:x}") # ff
print(f"Oct: {8:o}") # 10
# Alignment
print(f"{'left':<20}") # "left "
print(f"{'right':>20}") # " right"
print(f"{'center':^20}") # " center "
print(f"{'padded':*^20}") # "*******padded*******"
# Debug formatting (Python 3.8+)
x = 42
print(f"{x=}") # x=42
print(f"{x + 10=}") # x + 10=52.format() Method
python
# Positional arguments
print("{} is {} years old".format("Alice", 30))
# Named arguments
print("{name} is {age} years old".format(name="Alice", age=30))
# Index-based
print("{0} likes {1}. {0} is great.".format("Alice", "Python"))
# Number formatting
print("{:,.2f}".format(1234567.891)) # 1,234,567.89
# Accessing object attributes
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print("Point({0.x}, {0.y})".format(p)) # Point(3, 4)String Operations
Concatenation and Repetition
python
# Concatenation
first = "Hello"
last = "World"
full = first + " " + last
print(full) # Hello World
# Repetition
line = "-" * 30
print(line) # ------------------------------
border = "+-" * 15 + "+"
print(border) # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# Efficient concatenation with join (better than + in loops)
parts = []
for i in range(5):
parts.append(f"item_{i}")
result = ", ".join(parts)
print(result) # item_0, item_1, item_2, item_3, item_4String Iteration
python
text = "Python"
# Iterate over characters
for char in text:
print(char, end=" ")
# P y t h o n
# With index using enumerate
for i, char in enumerate(text):
print(f"{i}: {char}")
# 0: P 1: y 2: t 3: h 4: o 5: nCommon String Recipes
Check if String Contains Only Numbers
python
def is_valid_number(s):
"""Check if string is a valid number (including decimals and negatives)."""
try:
float(s)
return True
except ValueError:
return False
print(is_valid_number("42")) # True
print(is_valid_number("3.14")) # True
print(is_valid_number("-5")) # True
print(is_valid_number("abc")) # FalseCount Words in a String
python
text = "Python is a great programming language"
word_count = len(text.split())
print(f"Word count: {word_count}") # Word count: 6Reverse a String
python
text = "Python"
reversed_text = text[::-1]
print(reversed_text) # nohtyPCheck Palindrome
python
def is_palindrome(s):
s = s.lower().replace(" ", "")
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("A man a plan a canal Panama".replace(" ", ""))) # TrueSummary
- Strings are immutable sequences of characters
- Use indexing (
text[0]) and slicing (text[1:4]) to access parts of strings - Python provides 50+ string methods for manipulation, searching, and validation
- Use f-strings for modern, readable string formatting
- Use
join()instead of+for efficient string concatenation in loops - Strings support iteration, membership testing (
in), and comparison - Common operations:
split(),join(),strip(),replace(),find(),count()
Next, we'll learn about Python control flow with if-else statements.