Python Strings and Functions Reference: Methods & Examples
Python String Cheat Sheet
===========================
Python String Cheat Sheet
===========================
Strings are
- Indexed
- Iterable
- Immutable
Indexing & Slicing
———————————–
s = "python"
s[0] -> 'p'
s[-1] -> 'n'
Slicing:
s[start:end] -> s[1:4] = 'yth'
s[:3] -> 'pyt'
s[3:] -> 'hon'
s[::2] -> 'pto'
s[::-1] -> reversed stringImportant String Methods
———————————–
Case
s.upper()s.lower()s.capitalize()s.title()
Search
s.find("x")→ index or-1s.rfind("x")→ search from rights.index("x")→ raises an error if not found
Replace
s.replace("old", "new")
Strip (remove whitespace or characters)
s.strip()s.lstrip()s.rstrip()s.strip("x")→ removes ‘x’ from both ends
Count
s.count("a")
Check types
s.isalpha()s.isdigit()s.isalnum()s.isspace()
Split & Join
———————————–
Split
"a,b,c".split(",") -> ['a','b','c']
"hi there".split() -> ['hi','there']Join
",".join(['a','b','c']) -> 'a,b,c'
" ".join(['hi','there']) -> 'hi there'String Formatting
———————————–
f-strings (preferred)
name = "Dan"
f"Hello {name}"
f"{3.14159:.2f}" -> '3.14'format()
"{} {}".format("A", "B")
"{1} {0}".format("A", "B") -> 'B A'Old-style formatting
"%d" % 42
"%s" % "hello"
"%.2f" % 3.14String Immutability
———————————–
# NO:
s[0] = "X" -> ERROR
# YES: create a new string
s = "X" + s[1:]
===========================
Python Functions
===========================
Python Functions Cheat Sheet
—————————
Function Basics
def name(params):
statements
return valueFunctions must be defined before use.
Call
f(3, 4)
Return vs Print
- print() shows output
- return sends a value back
- A function with no
returnreturnsNone
—————————
Default Parameters
def f(a, b=5):
return a + bf(3) → 8
f(3, 2) → 5
Rules:
- Positional arguments first
- Keyword arguments after
- Default parameters must come after non-defaults
—————————
*args (variable number of positional arguments)
def f(*args):
print(args)f(1,2,3) → (1, 2, 3) # tuple
—————————
**kwargs (variable keyword arguments)
def f(**kwargs):
print(kwargs)f(a=1, b=2) → {'a': 1, 'b': 2} # dict
—————————
Multiple Return Values
def stats(x, y):
return x+y, x*ya, b = stats(3,4)
# returns a tuple
—————————
Scope (LEGB rule)
Local (inside function)
Enclosing
Global (defined top-level)
Built-in
Local variables shadow global variables.
global keyword
x = 10
def f():
global x
x = 5—————————
Functions Are Objects
Functions can be:
- assigned to variables
- stored in lists/dictionaries
- passed as arguments
x = f
x()—————————
Common Errors
- Missing colon after
def - Indentation errors
- Calling before definition
- Using undefined variables
- Returning
print()(returnsNone)
—————————
Docstrings
def f(x):
"""This function does something."""
return xhelp(f) shows the docstring.
—————————
Function Stubs
def f():
passPlaceholder function that does nothing.
—————————
Namespace & Scope Resolution
LEGB:
Local > Enclosing > Global > Built-in
—————————
Arbitrary Argument Lists
*args → tuple
**kwargs → dictionary
—————————
Functions with Loops / Branches
def f(n):
for i in range(n):
print(i)—————————
Dynamic Typing in Functions
Parameters accept any type:
def add(a, b):
return a + b # works for ints, strings, lists, etc.—————————
Print Functions
Functions can print instead of returning:
def show(x):
print(x)—————————
Reasons for Defining Functions
- Avoid repeating code (DRY)
- Reusable
- Organized
- Easier testing and debugging
