Skip to content
beginner Phase 1 · Python Basics

Tuples & Strings

Master immutable sequences, string methods, and formatting techniques.

1h
0 problems
Topic Progress 0%

Tuples

Creating Tuples

# Empty tuple
empty = ()

# Tuple with values
coordinates = (10, 20)

# Single element (note the comma!)
single = (42,)  # This is a tuple
not_tuple = (42)  # This is just an int!

# From list
tuple_from_list = tuple([1, 2, 3])

# From string
tuple_from_string = tuple('hello')  # ('h', 'e', 'l', 'l', 'o')

# Packing
point = 10, 20  # Parentheses optional

Tuple Unpacking

# Basic unpacking
point = (10, 20)
x, y = point
print(x, y)  # 10 20

# Swap variables
a, b = 1, 2
a, b = b, a  # a=2, b=1

# Star unpacking
first, *middle, last = (1, 2, 3, 4, 5)
# first=1, middle=[2, 3, 4], last=5

# Ignore values
_, name, _, age = ('id', 'Alice', 0, 30)
# name='Alice', age=30

Tuple Methods

numbers = (1, 2, 2, 3, 3, 3)

# Only two methods!
numbers.count(3)  # 3
numbers.index(2)  # 1 (first occurrence)

Named Tuples

from collections import namedtuple

# Define named tuple
Point = namedtuple('Point', ['x', 'y'])

# Create instance
p = Point(10, 20)
print(p.x, p.y)  # 10 20
print(p[0], p[1])  # 10 20

# Unpack
x, y = p

# Convert to dict
p_dict = p._asdict()  # {'x': 10, 'y': 20}

# Create new with changes
p2 = p._replace(x=30)  # Point(x=30, y=20)

When to Use Tuples

# ✅ Use tuples for:
# 1. Fixed collections
RGB = (255, 128, 0)

# 2. Dictionary keys
locations = {
    (40.7128, -74.0060): 'NYC',
    (34.0522, -118.2437): 'LA'
}

# 3. Multiple return values
def get_min_max(numbers):
    return min(numbers), max(numbers)

# 4. Unpacking
colors = ['red', 'green', 'blue']
for i, color in enumerate(colors):
    print(f'{i}: {color}')

# ❌ Use lists for:
# - Dynamic collections
# - Need to add/remove items
# - Ordered but mutable data

String Methods

Case Methods

s = 'Hello, World!'

s.upper()       # 'HELLO, WORLD!'
s.lower()       # 'hello, world!'
s.title()       # 'Hello, World!'
s.capitalize()  # 'Hello, world!'
s.swapcase()    # 'hELLO, wORLD!'
s.casefold()    # 'hello, world!' (aggressive lower)

Search Methods

s = 'Hello, World!'

s.find('World')     # 7
s.find('Python')    # -1 (not found)
s.rfind('l')        # 10 (last occurrence)

s.count('l')        # 3

s.startswith('He')  # True
s.endswith('!')      # True

# With start/end position
s.find('l', 0, 5)   # 2 (only search 'Hello')

Transformation Methods

s = '  Hello, World!  '

s.strip()       # 'Hello, World!'
s.lstrip()      # 'Hello, World!  '
s.rstrip()      # '  Hello, World!'
s.strip('! ')   # 'Hello, World'

s.replace('World', 'Python')  # 'Hello, Python!'
s.replace('l', 'L', 2)       # 'HeLLo, World!'

s.split(', ')   # ['Hello', 'World!']
s.split()       # ['Hello,', 'World!'] (split on whitespace)
s.rsplit(' ', 1) # ['Hello,', 'World!']

'-'.join(['a', 'b', 'c'])  # 'a-b-c'
' '.join(['Hello', 'World'])  # 'Hello World'

Checking Methods

'hello'.isalpha()    # True
'123'.isdigit()      # True
'123abc'.isalnum()   # True
'hello'.islower()    # True
'HELLO'.isupper()    # True
'  '.isspace()       # True
'Hello'.istitle()    # True

String Methods Table

Method Description Example
upper() Convert to uppercase 'hi'.upper()'HI'
lower() Convert to lowercase 'HI'.lower()'hi'
strip() Remove whitespace ' hi '.strip()'hi'
split() Split into list 'a,b'.split(',')['a','b']
join() Join list to string '-'.join(['a','b'])'a-b'
replace() Replace substring 'hi'.replace('i','I')'hI'
find() Find substring index 'hello'.find('ll')2
count() Count occurrences 'hello'.count('l')2

String Formatting

f-Strings (Python 3.6+)

name = 'Alice'
age = 30

# Basic
f'My name is {name} and I am {age} years old'

# Expressions
f'In 5 years, I will be {age + 5}'

# Format specifiers
pi = 3.14159
f'Pi is approximately {pi:.2f}'  # 'Pi is approximately 3.14'

f'{1000000:,}'  # '1,000,000'
f'{0.25:.0%}'   # '25%'
f'{100:>10}'    # '       100' (right-aligned, width 10)
f'{100:<10}'    # '100       ' (left-aligned)
f'{100:^10}'    # '   100    ' (center-aligned)
f'{42:05d}'     # '00042' (zero-padded)

# Debugging (Python 3.8+)
x = 42
f'{x = }'  # 'x = 42'

format() Method

# Positional
'My name is {} and I am {} years old'.format(name, age)

# Named
'My name is {name} and I am {age}'.format(name='Alice', age=30)

# Indexed
'{0} is {1}, {0} is {1}'.format('Alice', 'awesome')

# Format specifiers
'{:.2f}'.format(pi)  # '3.14'
'{:>10}'.format(100)  # '       100'

% Formatting (Old Style)

# Still works but not recommended
'My name is %s and I am %d years old' % (name, age)

'Pi is approximately %.2f' % pi  # 'Pi is approximately 3.14'

String Operations

# Concatenation
'Hello' + ' ' + 'World'  # 'Hello World'

# Repetition
'ha' * 3  # 'hahaha'

# Membership
'll' in 'Hello'  # True
'x' not in 'Hello'  # True

# Length
len('Hello')  # 5

# Iteration
for char in 'Hello':
    print(char)

# Join (more efficient than + for loops)
words = ['Hello', 'World']
' '.join(words)  # 'Hello World'

# ✅ Don't do this (creates many temporary strings)
result = ''
for word in words:
    result += word + ' '