---
title: "Python"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/python
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Python

Python is an interpreted, high-level programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.

7 Categories24 Sections48 ExamplesPublished: 01 Feb 2023Updated: 27 Feb 2025

PythonProgrammingScriptingObject-OrientedFunctionsClassesVariablesData TypesControl Flow

[Markdown for AI(opens in a new tab)](/python/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Programming Languages](/series/programming-languages)2/4

[PreviousDart](/cheatsheets/dart)[NextJavaScript](/cheatsheets/javascript)

All posts in this series (4)

Cheatsheets4

1.  [Dart](/cheatsheets/dart)
2.  [PythonYou are here](/cheatsheets/python)
3.  [JavaScript](/cheatsheets/javascript)
4.  [Go](/cheatsheets/go)

Python is an interpreted, high-level programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.

The sections below cover Python syntax, functions, classes, and common patterns.

[Getting Started](#category-getting-started)

-   [Basic Syntax](#section-basic-syntax)
-   [Data Types](#section-data-types)
-   [Numbers and Strings](#section-numbers-and-strings)

[Data Structures](#category-data-structures)

-   [Lists](#section-lists)
-   [Tuples](#section-tuples)
-   [Dictionaries](#section-dictionaries)
-   [Sets](#section-sets)

[Control Flow](#category-control-flow)

-   [Conditionals](#section-conditionals)
-   [Loops](#section-loops)
-   [List Comprehensions](#section-list-comprehensions)

[Functions and Scope](#category-functions-and-scope)

-   [Function Definition](#section-function-definition)
-   [Arguments](#section-arguments)
-   [Variable Scope](#section-variable-scope)

[Object-Oriented Programming](#category-object-oriented-programming)

-   [Classes](#section-classes)
-   [Inheritance](#section-inheritance)
-   [Special Methods](#section-special-methods)

[String Operations](#category-string-operations)

-   [String Slicing](#section-string-slicing)
-   [String Methods](#section-string-methods)
-   [String Formatting](#section-string-formatting)
-   [Regular Expressions](#section-regex)

[File I/O and Advanced](#category-file-io-and-advanced)

-   [File Operations](#section-file-operations)
-   [Context Managers](#section-context-managers)
-   [Exception Handling](#section-exception-handling)
-   [Lambdas and Higher-Order Functions](#section-lambdas-and-higher-order)

No commands found

Try adjusting your search term

## Getting Started

Fundamental Python concepts and syntax for beginners.

### Basic Syntax

Python fundamentals including print, variables, comments, and indentation.

#### Accessibility

Ensure output examples are clear and properly labeled.

#### Best Practices

-   Keep variable names descriptive and lowercase.
-   Use comments to explain the "why", not the "what".
-   Maintain consistent indentation (typically 4 spaces).

#### Common Errors

-   **IndentationError when defining blocks:** Use consistent indentation, typically 4 spaces per level.
-   **NameError for undefined variables:** Declare variables before using them.

#### Keywords

printvariablescommentsindentationsyntax

[Learn more](https://docs.python.org/3/reference/lexical_analysis.html)

#### Print statement and variables

Demonstrates variable assignment and f-string printing.

Code

```
1name = "Python"2version = 3.123print(f"Welcome to {name} {version}")
```

Execution

```
1python -c "name = 'Python'; version = 3.12; print(f'Welcome to {name} {version}')"
```

Output

```
1Welcome to Python 3.12
```

-   Python uses meaningful whitespace and indentation.
-   Variables are dynamically typed.

#### Comments and multiline strings

Shows different comment styles and how to write docstrings.

Code

```
1# This is a single-line comment2
3"""4This is a multiline comment5or docstring6"""7
8message = "Hello"  # inline comment9print(message)
```

Execution

```
1python -c "message = 'Hello'; print(message)"
```

Output

```
1Hello
```

-   Use '#' for single-line comments.
-   Use triple quotes for multiline comments or docstrings.

### Data Types

Python's built-in data types and type conversion.

#### Accessibility

Provide clear examples of type conversion with output.

#### Best Practices

-   Use explicit type conversion to avoid unexpected behavior.
-   Be aware of truthiness rules in conditionals.

#### Common Errors

-   **TypeError when operating on incompatible types:** Use type casting to convert before operations.

#### Keywords

data typesintfloatstrbooltype casting

[Learn more](https://docs.python.org/3/reference/datamodel.html)

#### Type casting and checking

Shows type casting and how to check variable types.

Code

```
1x = 422y = float(x)3z = str(x)4print(type(x), type(y), type(z))5print(y, z)
```

Execution

```
1python -c "x = 42; y = float(x); z = str(x); print(type(x), type(y), type(z)); print(y, z)"
```

Output

```
1<class 'int'> <class 'float'> <class 'str'>242.0 42
```

-   int(), float(), str(), bool() convert between types.
-   type() returns the data type of a variable.

#### None and boolean types

Demonstrates None, boolean types, and truthiness.

Code

```
1a = None2b = True3c = False4print(type(a), type(b), type(c))5print(bool(1), bool(0), bool(""))
```

Execution

```
1python -c "a = None; b = True; c = False; print(bool(1), bool(0), bool(''))"
```

Output

```
1True False False
```

-   None represents a null value.
-   Empty sequences and 0 evaluate to False.

### Numbers and Strings

Arithmetic operations, string slicing, and string methods.

#### Accessibility

Provide clear examples with labeled outputs.

#### Best Practices

-   Use f-strings for modern string formatting.
-   Remember that strings are immutable in Python.

#### Common Errors

-   **IndexError when slicing beyond string length:** Python slicing is safe and won't raise errors for out-of-range indices.

#### Keywords

arithmeticnumbersstringsslicingstring methods

[Learn more](https://docs.python.org/3/library/stdtypes.html#string-methods)

#### Arithmetic operations and string slicing

Shows arithmetic operators and string slicing with start:end:step syntax.

Code

```
1x = 102y = 33print(x + y, x - y, x * y, x / y, x // y, x % y, x ** y)4
5text = "Python"6print(text[0:3], text[-2:], text[::2])
```

Execution

```
1python -c "x = 10; y = 3; print(x + y, x - y, x * y, x / y, x // y, x % y, x ** y); text = 'Python'; print(text[0:3], text[-2:], text[::2])"
```

Output

```
113 7 30 3.3333333333333335 3 1 10002Pyt on Pto
```

-   / performs float division, // performs integer division.
-   Negative indices count from the end of the string.

#### String methods

Demonstrates common string methods like lower(), replace(), split(), and join().

Code

```
1text = "HELLO WORLD"2print(text.lower())3print(text.replace("WORLD", "Python"))4print(text.split())5print("_".join(["a", "b", "c"]))
```

Execution

```
1python -c "text = 'HELLO WORLD'; print(text.lower()); print(text.replace('WORLD', 'Python')); print(text.split()); print('_'.join(['a', 'b', 'c']))"
```

Output

```
1hello world2HELLO Python3['HELLO', 'WORLD']4a_b_c
```

-   String methods are case-sensitive for the method call.
-   split() returns a list of strings.

## Data Structures

Working with lists, tuples, dictionaries, and sets.

### Lists

Creating and manipulating ordered, mutable sequences.

#### Accessibility

Provide clear examples with list operations shown step-by-step.

#### Best Practices

-   Use list comprehensions for creating filtered or transformed lists.
-   Prefer extend() over append() when adding multiple items.

#### Common Errors

-   **IndexError when accessing out-of-range indices:** Check list length or use list slicing which is safe.

#### Keywords

listsappendpopinsertremoveindexing

[Learn more](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)

#### List creation and indexing

Demonstrates list creation, indexing, slicing, and the append() method.

Code

```
1items = [1, 2, 3, 4, 5]2print(items[0], items[-1])3print(items[1:3], items[::2])4items.append(6)5print(items)
```

Execution

```
1python -c "items = [1, 2, 3, 4, 5]; print(items[0], items[-1]); print(items[1:3], items[::2]); items.append(6); print(items)"
```

Output

```
11 52[2, 3] [1, 3, 5]3[1, 2, 3, 4, 5, 6]
```

-   Lists are mutable and can be modified after creation.
-   Use negative indices to access from the end.

#### List methods and operations

Shows remove(), pop(), and extend() methods.

Code

```
1items = [1, 2, 3, 2, 4]2items.remove(2)3print(items)4items.pop()5print(items)6items.extend([5, 6])7print(items)
```

Execution

```
1python -c "items = [1, 2, 3, 2, 4]; items.remove(2); print(items); items.pop(); print(items); items.extend([5, 6]); print(items)"
```

Output

```
1[1, 3, 2, 4]2[1, 3, 2]3[1, 3, 2, 5, 6]
```

-   remove() removes the first occurrence of a value.
-   pop() removes and returns the last element.
-   extend() adds multiple elements to the list.

### Tuples

Immutable sequences and tuple unpacking.

#### Accessibility

Show tuple operations with clear outputs.

#### Best Practices

-   Use tuples when you need immutable sequences.
-   Use tuple unpacking to improve code readability.

#### Common Errors

-   **TypeError when trying to modify a tuple:** Tuples are immutable; create a new tuple instead.

#### Keywords

tuplesimmutableunpackingfixed size

[Learn more](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences)

#### Tuple creation and unpacking

Creates tuples and demonstrates unpacking values into variables.

Code

```
1point = (10, 20)2x, y = point3print(f"x={x}, y={y}")4
5data = (1, 2, 3)6print(data[0], data[-1], len(data))
```

Execution

```
1python -c "point = (10, 20); x, y = point; print(f'x={x}, y={y}'); data = (1, 2, 3); print(data[0], data[-1], len(data))"
```

Output

```
1x=10, y=2021 3 3
```

-   Tuples are immutable; they cannot be modified after creation.
-   Unpacking allows assigning tuple values to multiple variables.

#### Tuple operations

Demonstrates tuple concatenation and repetition.

Code

```
1t1 = (1, 2)2t2 = (3, 4)3t3 = t1 + t24print(t3)5print(t3 * 2)6print((5,) == (5))
```

Execution

```
1python -c "t1 = (1, 2); t2 = (3, 4); t3 = t1 + t2; print(t3); print(t3 * 2); print((5,) == (5))"
```

Output

```
1(1, 2, 3, 4)2(1, 2, 3, 4, 1, 2, 3, 4)3False
```

-   Use a trailing comma (5,) to create a single-element tuple.

### Dictionaries

Key-value pairs and dictionary operations.

#### Accessibility

Provide clear examples of dict operations.

#### Best Practices

-   Use get() to safely access dictionary values.
-   Use dictionary comprehensions for creating dictionaries.

#### Common Errors

-   **KeyError when accessing non-existent keys:** Use get() or check if key exists with 'in'.

#### Keywords

dictionariesdictkeysvaluesitemsget

[Learn more](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)

#### Dictionary creation and access

Shows dictionary creation and access using \[\] and get().

Code

```
1person = {"name": "Alice", "age": 30, "city": "NYC"}2print(person["name"])3print(person.get("age"))4print(person.get("email", "Not found"))
```

Execution

```
1python -c "person = {'name': 'Alice', 'age': 30, 'city': 'NYC'}; print(person['name']); print(person.get('age')); print(person.get('email', 'Not found'))"
```

Output

```
1Alice2303Not found
```

-   Use get() to safely access keys with a default value.
-   get() returns None if the key is not found and no default is provided.

#### Dictionary modification and iteration

Demonstrates adding, deleting, and iterating over dictionary entries.

Code

```
1d = {"a": 1, "b": 2}2d["c"] = 33del d["a"]4print(d)5print(d.keys(), d.values())6for key, value in d.items():7  print(f"{key}: {value}")
```

Execution

```
1python -c "d = {'a': 1, 'b': 2}; d['c'] = 3; del d['a']; print(d); print(list(d.keys()), list(d.values())); [(print(f'{k}: {v}')) for k, v in d.items()]"
```

Output

```
1{'b': 2, 'c': 3}2dict_keys(['b', 'c']) dict_values([2, 3])3b: 24c: 3
```

-   Use del to remove key-value pairs.
-   items() returns tuples of (key, value) pairs.

### Sets

Unordered collections of unique elements.

#### Accessibility

Show set operations with clear outputs.

#### Best Practices

-   Use sets to remove duplicates from lists.
-   Use sets for membership testing (faster than lists).

#### Common Errors

-   **KeyError when removing non-existent elements:** Use discard() instead of remove() for safe removal.

#### Keywords

setsuniqueunionintersectiondifference

[Learn more](https://docs.python.org/3/tutorial/datastructures.html#sets)

#### Set creation and operations

Shows set creation (duplicates removed) and add/remove operations.

Code

```
1s = {1, 2, 3, 3, 4}2print(s)3s.add(5)4s.remove(2)5print(s)
```

Execution

```
1python -c "s = {1, 2, 3, 3, 4}; print(s); s.add(5); s.remove(2); print(s)"
```

Output

```
1{1, 2, 3, 4}2{1, 3, 4, 5}
```

-   Sets automatically remove duplicates.
-   Sets are unordered, so iteration order is not guaranteed.

#### Set operations

Demonstrates union (|), intersection (&), and difference (-) operations.

Code

```
1a = {1, 2, 3}2b = {3, 4, 5}3print(a | b)  # union4print(a & b)  # intersection5print(a - b)  # difference
```

Execution

```
1python -c "a = {1, 2, 3}; b = {3, 4, 5}; print(a | b); print(a & b); print(a - b)"
```

Output

```
1{1, 2, 3, 4, 5}2{3}3{1, 2}
```

-   Use pipes |, ampersand &, and minus - for set operations.

## Control Flow

Conditionals, loops, and list comprehensions.

### Conditionals

if/elif/else statements and logical operators.

#### Accessibility

Provide clear conditional examples with outputs.

#### Best Practices

-   Keep conditional logic simple and readable.
-   Avoid deeply nested conditionals.

#### Common Errors

-   **IndentationError in conditional blocks:** Maintain consistent indentation (4 spaces) for conditional blocks.

#### Keywords

conditionalsifelifelsecomparisonlogical operators

[Learn more](https://docs.python.org/3/tutorial/controlflow.html)

#### if/elif/else statements

Shows if/elif/else conditional logic.

Code

```
1x = 152if x < 10:3  print("Less than 10")4elif x < 20:5  print("Between 10 and 20")6else:7  print("20 or more")
```

Execution

```
1python -c "x = 15; print('Between 10 and 20' if x >= 10 and x < 20 else ('Less than 10' if x < 10 else '20 or more'))"
```

Output

```
1Between 10 and 20
```

-   Each conditional block must be indented.
-   Use elif for multiple conditions.

#### Comparison and logical operators

Demonstrates logical operators (and, or, not) and membership testing (in).

Code

```
1x = 52print(x > 3 and x < 10)3print(x == 5 or x == 10)4print(not (x == 0))5print(x in [1, 2, 5, 10])
```

Execution

```
1python -c "x = 5; print(x > 3 and x < 10); print(x == 5 or x == 10); print(not (x == 0)); print(x in [1, 2, 5, 10])"
```

Output

```
1True2True3True4True
```

-   Use 'and', 'or', 'not' for boolean operations.
-   Use 'in' to check membership in lists, strings, etc.

### Loops

for and while loops with break and continue.

#### Accessibility

Show loop examples with clear iteration shown.

#### Best Practices

-   Use for loops for iterating over sequences.
-   Use while loops for condition-based repetition.

#### Common Errors

-   **Infinite loop with while True:** Add a break condition or a counter that exits the loop.

#### Keywords

loopsforwhilebreakcontinuerange

[Learn more](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)

#### for loop with range and lists

Shows for loops iterating over ranges and lists.

Code

```
1for i in range(3):2  print(f"Iteration {i}")3
4for item in ["a", "b", "c"]:5  print(item)
```

Execution

```
1python -c "for i in range(3): print(f'Iteration {i}'); print('---'); [print(item) for item in ['a', 'b', 'c']]"
```

Output

```
1Iteration 02Iteration 13Iteration 24---5a6b7c
```

-   range(n) generates numbers from 0 to n-1.
-   for loops automatically iterate over sequences.

#### Loop control with break and continue

Demonstrates break (exit loop) and continue (skip iteration).

Code

```
1for i in range(5):2  if i == 2:3    continue4  if i == 4:5    break6  print(i)
```

Execution

```
1python -c "for i in range(5):\n  if i == 2:\n    continue\n  if i == 4:\n    break\n  print(i)"
```

Output

```
102133
```

-   continue skips the current iteration.
-   break exits the loop entirely.

### List Comprehensions

Concise syntax for creating and filtering lists.

#### Accessibility

Provide clear list comprehension examples.

#### Best Practices

-   Use list comprehensions for simple transformations.
-   Break complex comprehensions into multiple lines for readability.

#### Common Errors

-   **Complex comprehensions that are hard to read:** Convert back to for loops if comprehension becomes too complex.

#### Keywords

list comprehensionlistfiltertransformnested

[Learn more](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)

#### Basic list comprehension

Shows list comprehension with transformation and filtering.

Code

```
1squares = [x**2 for x in range(5)]2print(squares)3
4evens = [x for x in range(10) if x % 2 == 0]5print(evens)
```

Execution

```
1python -c "squares = [x**2 for x in range(5)]; print(squares); evens = [x for x in range(10) if x % 2 == 0]; print(evens)"
```

Output

```
1[0, 1, 4, 9, 16]2[0, 2, 4, 6, 8]
```

-   List comprehensions are more concise than for loops.
-   Add if clause for filtering elements.

#### Nested list comprehension

Demonstrates nested list comprehensions and flattening matrices.

Code

```
1matrix = [[i*j for j in range(3)] for i in range(3)]2print(matrix)3
4flat = [x for row in matrix for x in row]5print(flat)
```

Execution

```
1python -c "matrix = [[i*j for j in range(3)] for i in range(3)]; print(matrix); flat = [x for row in matrix for x in row]; print(flat)"
```

Output

```
1[[0, 0, 0], [0, 1, 2], [0, 2, 4]]2[0, 0, 0, 0, 1, 2, 0, 2, 4]
```

-   Nested comprehensions can be complex; prioritize readability.

## Functions and Scope

Defining functions, arguments, and variable scope.

### Function Definition

def keyword, parameters, return statements, and docstrings.

#### Accessibility

Provide clear function examples with inputs and outputs.

#### Best Practices

-   Write clear, concise functions with single responsibilities.
-   Use docstrings to document function behavior.

#### Common Errors

-   **UnboundLocalError when accessing outer variable:** Use nonlocal or global keywords as needed.

#### Keywords

functiondefreturndocstringparameter

[Learn more](https://docs.python.org/3/tutorial/controlflow.html#defining-functions)

#### Basic function definition

Demonstrates basic function definition with parameters and return statement.

Code

```
1def greet(name):2  """Greet a person by name."""3  return f"Hello, {name}!"4
5print(greet("Alice"))
```

Execution

```
1python -c "def greet(name):\n  return f'Hello, {name}!'\nprint(greet('Alice'))"
```

Output

```
1Hello, Alice!
```

-   Functions are defined with the def keyword.
-   Docstrings document function purpose and usage.

#### Function with default arguments

Shows functions with default parameter values.

Code

```
1def add(a, b=0, c=0):2  return a + b + c3
4print(add(1))5print(add(1, 2))6print(add(1, 2, 3))
```

Execution

```
1python -c "def add(a, b=0, c=0):\n  return a + b + c\nprint(add(1)); print(add(1, 2)); print(add(1, 2, 3))"
```

Output

```
112336
```

-   Default parameters must come after required parameters.
-   Default values are evaluated once at function definition.

### Arguments

Positional arguments, keyword arguments, \*args, and \*\*kwargs.

#### Accessibility

Show different argument passing styles with examples.

#### Best Practices

-   Use \*args and \*\*kwargs for flexible function signatures.
-   Document what arguments your function expects.

#### Common Errors

-   **TypeError due to incorrect number of arguments:** Check the function signature and pass the arguments it expects.

#### Keywords

argumentspositionalkeyword\*args\*\*kwargsvariadic

[Learn more](https://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions)

#### Positional and keyword arguments

Shows positional and keyword argument passing.

Code

```
1def describe(name, age, city):2  return f"{name} is {age} years old and lives in {city}"3
4print(describe("Alice", 30, "NYC"))5print(describe(name="Bob", city="LA", age=25))
```

Execution

```
1python -c "def describe(name, age, city):\n  return f'{name} is {age} years old and lives in {city}'\nprint(describe('Alice', 30, 'NYC')); print(describe(name='Bob', city='LA', age=25))"
```

Output

```
1Alice is 30 years old and lives in NYC2Bob is 25 years old and lives in LA
```

-   Keyword arguments can be passed in any order.
-   Mix positional and keyword arguments by passing positional first.

#### Variable length arguments (\*args and \*\*kwargs)

Demonstrates \*args for variable positional arguments and \*\*kwargs for variable keyword arguments.

Code

```
1def sum_numbers(*args):2  return sum(args)3
4def print_info(**kwargs):5  for key, value in kwargs.items():6    print(f"{key}: {value}")7
8print(sum_numbers(1, 2, 3, 4))9print_info(name="Alice", age=30, city="NYC")
```

Execution

```
1python -c "def sum_numbers(*args):\n  return sum(args)\ndef print_info(**kwargs):\n  for key, value in kwargs.items():\n    print(f'{key}: {value}')\nprint(sum_numbers(1, 2, 3, 4)); print_info(name='Alice', age=30, city='NYC')"
```

Output

```
1102name: Alice3age: 304city: NYC
```

-   \*args collects positional arguments as a tuple.
-   \*\*kwargs collects keyword arguments as a dictionary.

### Variable Scope

Local, global, and nonlocal variables.

#### Accessibility

Provide clear scope examples with variable access.

#### Best Practices

-   Minimize use of global variables for code clarity.
-   Prefer passing arguments and returning values.

#### Common Errors

-   **UnboundLocalError accessing variable before assignment:** Use global or nonlocal keywords to access outer scope variables.

#### Keywords

scopelocalglobalnonlocalnamespace

[Learn more](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces)

#### Local and global scope

Shows local variables shadowing global variables.

Code

```
1x = "global"2
3def func():4  x = "local"5  print(x)6
7func()8print(x)
```

Execution

```
1python -c "x = 'global'\ndef func():\n  x = 'local'\n  print(x)\nfunc(); print(x)"
```

Output

```
1local2global
```

-   Local variables are created when assigned in a function.
-   Accessing a global variable requires the global keyword to modify it.

#### Global and nonlocal keywords

Demonstrates global and nonlocal keywords to modify variables from enclosing scopes.

Code

```
1x = 02
3def outer():4  y = 15  def inner():6    nonlocal y7    global x8    x = 109    y = 210  inner()11  print(f"y={y}")12
13outer()14print(f"x={x}")
```

Execution

```
1python -c "x = 0\ndef outer():\n  y = 1\n  def inner():\n    nonlocal y\n    global x\n    x = 10\n    y = 2\n  inner()\n  print(f'y={y}')\nouter(); print(f'x={x}')"
```

Output

```
1y=22x=10
```

-   global allows modifying module-level variables.
-   nonlocal allows modifying variables in enclosing function scopes.

## Object-Oriented Programming

Classes, inheritance, and special methods.

### Classes

Class definition, \_\_init\_\_, self, and instance methods.

#### Accessibility

Provide clear class examples with object instantiation.

#### Best Practices

-   Use clear, descriptive class and method names.
-   Initialize all instance attributes in \_\_init\_\_.

#### Common Errors

-   **TypeError when forgetting self parameter:** Always include self as the first parameter in methods.

#### Keywords

classobject\_\_init\_\_selfmethodinstance

[Learn more](https://docs.python.org/3/tutorial/classes.html)

#### Basic class definition

Demonstrates class definition with \_\_init\_\_ constructor and instance methods.

Code

```
1class Dog:2  def __init__(self, name, age):3    self.name = name4    self.age = age5
6  def bark(self):7    return f"{self.name} says Woof!"8
9dog = Dog("Buddy", 3)10print(dog.bark())
```

Execution

```
1python -c "class Dog:\n  def __init__(self, name, age):\n    self.name = name\n    self.age = age\n  def bark(self):\n    return f'{self.name} says Woof!'\ndog = Dog('Buddy', 3); print(dog.bark())"
```

Output

```
1Buddy says Woof!
```

-   \_\_init\_\_ is the constructor called when creating an object.
-   self refers to the instance and must be the first parameter.

#### Instance attributes and methods

Shows instance attributes and methods that modify object state.

Code

```
1class Counter:2  def __init__(self):3    self.count = 04
5  def increment(self):6    self.count += 17    return self.count8
9c = Counter()10print(c.increment())11print(c.increment())12print(c.count)
```

Execution

```
1python -c "class Counter:\n  def __init__(self):\n    self.count = 0\n  def increment(self):\n    self.count += 1\n    return self.count\nc = Counter(); print(c.increment()); print(c.increment()); print(c.count)"
```

Output

```
112232
```

-   Instance attributes are created in \_\_init\_\_ or assigned later.
-   Methods can access and modify instance attributes.

### Inheritance

Class inheritance, super(), and method overriding.

#### Accessibility

Provide clear inheritance examples with method overriding.

#### Best Practices

-   Use inheritance for code reuse and logical hierarchies.
-   Prefer composition over inheritance when appropriate.

#### Common Errors

-   **TypeError in super().\_\_init\_\_() call:** Check that the parent class defines \_\_init\_\_ and takes the parameters passed to it.

#### Keywords

inheritanceparentchildsuperoverrideextend

[Learn more](https://docs.python.org/3/tutorial/classes.html#inheritance)

#### Class inheritance and super()

Shows class inheritance and method overriding.

Code

```
1class Animal:2  def __init__(self, name):3    self.name = name4
5  def speak(self):6    return f"{self.name} makes a sound"7
8class Dog(Animal):9  def speak(self):10    return f"{self.name} barks"11
12dog = Dog("Rex")13print(dog.speak())
```

Execution

```
1python -c "class Animal:\n  def __init__(self, name):\n    self.name = name\n  def speak(self):\n    return f'{self.name} makes a sound'\nclass Dog(Animal):\n  def speak(self):\n    return f'{self.name} barks'\ndog = Dog('Rex'); print(dog.speak())"
```

Output

```
1Rex barks
```

-   Child classes inherit attributes and methods from parent classes.
-   Override methods by redefining them in the child class.

#### Using super() to call parent methods

Demonstrates super() to call parent class methods.

Code

```
1class Animal:2  def __init__(self, name):3    self.name = name4
5class Dog(Animal):6  def __init__(self, name, breed):7    super().__init__(name)8    self.breed = breed9
10dog = Dog("Buddy", "Golden")11print(f"{dog.name} is a {dog.breed}")
```

Execution

```
1python -c "class Animal:\n  def __init__(self, name):\n    self.name = name\nclass Dog(Animal):\n  def __init__(self, name, breed):\n    super().__init__(name)\n    self.breed = breed\ndog = Dog('Buddy', 'Golden'); print(f'{dog.name} is a {dog.breed}')"
```

Output

```
1Buddy is a Golden
```

-   super() provides access to parent class methods.
-   Always call super().\_\_init\_\_() to initialize parent attributes.

### Special Methods

\_\_str\_\_, \_\_repr\_\_, \_\_len\_\_, \_\_getitem\_\_, and other dunder methods.

#### Accessibility

Show special methods with clear output examples.

#### Best Practices

-   Implement \_\_str\_\_ for readable output.
-   Use special methods to make objects behave like built-in types.

#### Common Errors

-   **Objects not indexable when \_\_getitem\_\_ is missing:** Implement \_\_getitem\_\_ to enable indexing.

#### Keywords

dunder methodspecial method\_\_str\_\_\_\_repr\_\_\_\_len\_\_\_\_getitem\_\_

[Learn more](https://docs.python.org/3/reference/datamodel.html#special-method-names)

#### \_\_str\_\_ and \_\_repr\_\_ methods

Shows \_\_str\_\_ for user-friendly representation and \_\_repr\_\_ for development.

Code

```
1class Point:2  def __init__(self, x, y):3    self.x = x4    self.y = y5
6  def __str__(self):7    return f"Point({self.x}, {self.y})"8
9  def __repr__(self):10    return f"Point(x={self.x}, y={self.y})"11
12p = Point(3, 4)13print(str(p))14print(repr(p))
```

Execution

```
1python -c "class Point:\n  def __init__(self, x, y):\n    self.x = x\n    self.y = y\n  def __str__(self):\n    return f'Point({self.x}, {self.y})'\np = Point(3, 4); print(str(p))"
```

Output

```
1Point(3, 4)
```

-   \_\_str\_\_ returns a user-friendly string representation.
-   \_\_repr\_\_ returns a developer-friendly representation (ideally recreatable).

#### \_\_len\_\_ and \_\_getitem\_\_ methods

Demonstrates \_\_len\_\_ for len() and \_\_getitem\_\_ for indexing.

Code

```
1class SimpleList:2  def __init__(self, items):3    self.items = items4
5  def __len__(self):6    return len(self.items)7
8  def __getitem__(self, index):9    return self.items[index]10
11lst = SimpleList([1, 2, 3])12print(len(lst))13print(lst[0])14print(lst[-1])
```

Execution

```
1python -c "class SimpleList:\n  def __init__(self, items):\n    self.items = items\n  def __len__(self):\n    return len(self.items)\n  def __getitem__(self, index):\n    return self.items[index]\nlst = SimpleList([1, 2, 3]); print(len(lst)); print(lst[0]); print(lst[-1])"
```

Output

```
132133
```

-   \_\_len\_\_ enables len() function on custom objects.
-   \_\_getitem\_\_ enables indexing and slicing.

## String Operations

Slicing, methods, formatting, and regular expressions.

### String Slicing

String slicing with start:end:step and negative indexing.

#### Accessibility

Show slicing examples with clear output.

#### Best Practices

-   Use negative indices for accessing from the end.
-   Reverse strings with \[::-1\].

#### Common Errors

-   **Off-by-one errors in slicing:** Remember that end index is exclusive.

#### Keywords

slicingstringindexingsubstringreverse

[Learn more](https://docs.python.org/3/tutorial/introduction.html#strings)

#### String slicing with indices

Demonstrates string slicing with positive/negative indices and step values.

Code

```
1s = "Python"2print(s[0:3])3print(s[3:])4print(s[-3:])5print(s[::2])6print(s[::-1])
```

Execution

```
1python -c "s = 'Python'; print(s[0:3]); print(s[3:]); print(s[-3:]); print(s[::2]); print(s[::-1])"
```

Output

```
1Pyt2hon3thon4Pto5nohtyP
```

-   s\[start:end\] slices from start to end-1.
-   Negative indices count from the end.
-   Step value (third parameter) allows skipping characters.

#### Advanced slicing techniques

Shows practical slicing use cases.

Code

```
1s = "Hello World"2print(s[6:11])3print(s[-5:])4print(s[::3])5print(s[1::2])
```

Execution

```
1python -c "s = 'Hello World'; print(s[6:11]); print(s[-5:]); print(s[::3]); print(s[1::2])"
```

Output

```
1World2World3HloWrd4elo ol
```

-   Slicing is safe even with out-of-range indices.

### String Methods

Methods like upper(), lower(), split(), join(), replace(), find(), strip().

#### Accessibility

Provide clear examples of each method.

#### Best Practices

-   Use split() and join() for string parsing and formatting.
-   Use replace() for simple text substitutions.

#### Common Errors

-   **Expecting string when split() returns a list:** Remember that split() returns a list, not a string.

#### Keywords

string methodsupperlowersplitjoinreplacefindstrip

[Learn more](https://docs.python.org/3/library/stdtypes.html#string-methods)

#### Case conversion and whitespace handling

Shows case conversion and whitespace removal methods.

Code

```
1s = "  Hello World  "2print(s.upper())3print(s.lower())4print(s.strip())5print(s.lstrip())6print(s.rstrip())
```

Execution

```
1python -c "s = '  Hello World  '; print(s.upper()); print(s.lower()); print(s.strip()); print(repr(s.lstrip())); print(repr(s.rstrip()))"
```

Output

```
1  HELLO WORLD2  hello world3Hello World4'Hello World  '5'  Hello World'
```

-   strip() removes leading and trailing whitespace.
-   lstrip() and rstrip() remove from left and right only.

#### String splitting, joining, and replacement

Demonstrates split(), join(), replace(), and find() methods.

Code

```
1text = "apple,banana,cherry"2items = text.split(",")3print(items)4print("-".join(items))5print(text.replace("apple", "orange"))6print(text.find("banana"))
```

Execution

```
1python -c "text = 'apple,banana,cherry'; items = text.split(','); print(items); print('-'.join(items)); print(text.replace('apple', 'orange')); print(text.find('banana'))"
```

Output

```
1['apple', 'banana', 'cherry']2apple-banana-cherry3orange,banana,cherry46
```

-   split() returns a list of substrings.
-   join() concatenates list items with a separator.
-   find() returns the index of substring or -1 if not found.

### String Formatting

f-strings, .format(), % formatting, and string interpolation.

#### Accessibility

Show different formatting methods with clear output.

#### Best Practices

-   Use f-strings for modern Python (3.6+).
-   Format numbers appropriately for their domain (money, percentages, etc.).

#### Common Errors

-   **KeyError in .format() with wrong placeholder names:** Match placeholder names to the argument names or indices.

#### Keywords

formattingf-stringformatinterpolation%

[Learn more](https://docs.python.org/3/tutorial/inputandoutput.html#fancier-output-formatting)

#### f-strings and .format() method

Shows f-strings (modern) and .format() (older style) formatting.

Code

```
1name = "Alice"2age = 303city = "NYC"4
5print(f"Name: {name}, Age: {age}, City: {city}")6print("Name: {}, Age: {}, City: {}".format(name, age, city))7print("Name: {0}, Age: {1}, City: {2}".format(name, age, city))
```

Execution

```
1python -c "name = 'Alice'; age = 30; city = 'NYC'; print(f'Name: {name}, Age: {age}, City: {city}')"
```

Output

```
1Name: Alice, Age: 30, City: NYC
```

-   f-strings are preferred for their readability and performance.
-   .format() provides indexed and named placeholders.

#### Formatting numbers and expressions

Demonstrates formatting with precision, currency, and different bases.

Code

```
1pi = 3.141592price = 19.953x = 104
5print(f"Pi: {pi:.2f}")6print(f"Price: ${price:.2f}")7print(f"Expression: {x * 2}")8print(f"Hex: {x:x}")
```

Execution

```
1python -c "pi = 3.14159; price = 19.95; x = 10; print(f'Pi: {pi:.2f}'); print(f'Price: ${price:.2f}'); print(f'Expression: {x * 2}'); print(f'Hex: {x:x}')"
```

Output

```
1Pi: 3.142Price: $19.953Expression: 204Hex: a
```

-   Use :f for float formatting with .2f for 2 decimal places.
-   f-strings support full Python expressions inside {}.

### Regular Expressions

Pattern matching with re.match(), re.search(), re.sub(), re.compile().

#### Accessibility

Show regex examples with clear pattern explanations.

#### Best Practices

-   Use raw strings (r'...') for regex patterns to avoid escaping issues.
-   Compile patterns if using them multiple times.

#### Common Errors

-   **AttributeError when match() returns None:** Check if match is None before calling .group().

#### Keywords

regexregular expressionpatternmatchsearchsubstitute

[Learn more](https://docs.python.org/3/library/re.html)

#### Basic pattern matching

Shows match(), search(), and findall() for pattern matching.

Code

```
1import re2
3text = "Hello 123"4print(re.match(r'\w+', text))5print(re.search(r'\d+', text))6print(re.findall(r'\w+', text))
```

Execution

```
1python -c "import re; text = 'Hello 123'; m = re.match(r'\\w+', text); print(m.group() if m else None); m = re.search(r'\\d+', text); print(m.group() if m else None); print(re.findall(r'\\w+', text))"
```

Output

```
1Hello21233['Hello', '123']
```

-   match() checks at the beginning of the string.
-   search() finds the first match anywhere in the string.
-   findall() returns all matches as a list.

#### Pattern substitution and compilation

Demonstrates sub() for replacement and compile() for reusable patterns.

Code

```
1import re2
3text = "The date is 2025-02-27"4print(re.sub(r'\d+', '#', text))5
6pattern = re.compile(r'[a-z]+')7print(pattern.findall("abc123def456"))
```

Execution

```
1python -c "import re; text = 'The date is 2025-02-27'; print(re.sub(r'\\d+', '#', text)); pattern = re.compile(r'[a-z]+'); print(pattern.findall('abc123def456'))"
```

Output

```
1The date is #-#-#2['abc', 'def']
```

-   sub() replaces matches with a replacement string.
-   compile() creates a pattern object for reuse.

## File I/O and Advanced

File operations, context managers, exception handling, and higher-order functions.

### File Operations

open(), read(), write(), readlines(), and seek().

#### Accessibility

Show file operations with clear examples.

#### Best Practices

-   Always use with statement for automatic file closing.
-   Choose appropriate file modes (r, w, a, r+, etc.).

#### Common Errors

-   **FileNotFoundError when reading non-existent files:** Check the file path and confirm the file exists before reading.

#### Keywords

fileopenreadwritereadlinesseek

[Learn more](https://docs.python.org/3/tutorial/inputandoutput.html#reading-and-writing-files)

#### Reading and writing files

Demonstrates writing to and reading from files.

Code

```
1# Writing to a file2with open("example.txt", "w") as f:3  f.write("Hello, Python!")4
5# Reading from a file6with open("example.txt", "r") as f:7  content = f.read()8  print(content)
```

Execution

```
1python -c "with open('/tmp/example.txt', 'w') as f: f.write('Hello, Python!'); f = open('/tmp/example.txt', 'r'); content = f.read(); f.close(); print(content)"
```

Output

```
1Hello, Python!
```

-   Use "w" mode for writing (overwrites existing file).
-   Use "r" mode for reading.
-   Always close files or use with statement.

#### Reading lines and file positioning

Shows readlines() for reading multiple lines.

Code

```
1# Writing multiple lines2with open("lines.txt", "w") as f:3  f.write("Line 1\nLine 2\nLine 3")4
5# Reading lines6with open("lines.txt", "r") as f:7  lines = f.readlines()8  for line in lines:9    print(line.strip())
```

Execution

```
1python -c "with open('/tmp/lines.txt', 'w') as f: f.write('Line 1\\nLine 2\\nLine 3'); f = open('/tmp/lines.txt', 'r'); lines = f.readlines(); f.close(); [print(line.strip()) for line in lines]"
```

Output

```
1Line 12Line 23Line 3
```

-   readlines() returns a list of lines with newline characters.
-   strip() removes leading/trailing whitespace including newlines.

### Context Managers

Using with statement for automatic resource management.

#### Accessibility

Explain context manager benefits clearly.

#### Best Practices

-   Always use with statement for file operations.
-   Create custom context managers for resource management.

#### Common Errors

-   **Resource not released without with statement:** Always use with statement for file operations.

#### Keywords

context managerwithcontextlibresource management

[Learn more](https://docs.python.org/3/library/contextlib.html)

#### Context manager with open()

Shows how with statement automatically closes files.

Code

```
1with open("data.txt", "w") as f:2  f.write("Important data")3  print(f.closed)4print(f.closed)
```

Execution

```
1python -c "f = None; exec('with open(\\\"/tmp/data.txt\\\", \\\"w\\\") as f: f.write(\\\"Important data\\\"); print(f.closed)'); print(f.closed)"
```

Output

```
1False2True
```

-   with statement runs cleanup even if exceptions occur.
-   File is closed when exiting the with block.

#### Custom context manager

Demonstrates creating custom context managers with @contextmanager decorator.

Code

```
1from contextlib import contextmanager2
3@contextmanager4def timer():5  import time6  start = time.time()7  yield8  print(f"Elapsed: {time.time() - start:.2f}s")9
10with timer():11  sum(range(1000000))
```

Execution

```
1python -c "from contextlib import contextmanager; import time\n@contextmanager\ndef timer():\n  start = time.time()\n  yield\n  print(f'Elapsed: {time.time() - start:.2f}s')\nwith timer(): sum(range(1000000))"
```

Output

```
1Elapsed: 0.01s
```

-   @contextmanager simplifies context manager creation.
-   Code before yield runs on entry, after yield on exit.

### Exception Handling

try/except/else/finally blocks and raising exceptions.

#### Accessibility

Provide clear exception handling examples.

#### Best Practices

-   Catch specific exceptions, not generic Exception.
-   Use finally for cleanup code that must always run.

#### Common Errors

-   **Catching too broad exception types:** Catch specific exception types to avoid masking bugs.

#### Keywords

exceptiontryexceptelsefinallyraise

[Learn more](https://docs.python.org/3/tutorial/errors.html)

#### try/except blocks

Shows try/except blocks for handling specific exceptions.

Code

```
1try:2  x = int("not a number")3except ValueError as e:4  print(f"Error: {e}")5
6try:7  result = 10 / 08except ZeroDivisionError:9  print("Cannot divide by zero")
```

Execution

```
1python -c "try:\n  x = int('not a number')\nexcept ValueError as e:\n  print(f'Error: {e}'); try:\n  result = 10 / 0\nexcept ZeroDivisionError:\n  print('Cannot divide by zero')"
```

Output

```
1Error: invalid literal for int() with base 10: 'not a number'2Cannot divide by zero
```

-   except block executes if the specific exception occurs.
-   Use 'as' to capture exception details.

#### try/except/else/finally

Demonstrates else (no exception) and finally (always executes) blocks.

Code

```
1try:2  x = 10 / 23except ZeroDivisionError:4  print("Error")5else:6  print(f"Result: {x}")7finally:8  print("Cleanup")
```

Execution

```
1python -c "try:\n  x = 10 / 2\nexcept ZeroDivisionError:\n  print('Error')\nelse:\n  print(f'Result: {x}')\nfinally:\n  print('Cleanup')"
```

Output

```
1Result: 5.02Cleanup
```

-   else block executes if no exception occurs.
-   finally block always executes for cleanup.

### Lambdas and Higher-Order Functions

Lambda functions, map(), filter(), sorted(), and functional programming.

#### Accessibility

Show practical examples of functional techniques.

#### Best Practices

-   Use list comprehensions instead of map()/filter() for readability.
-   Keep lambdas simple; use def for complex functions.

#### Common Errors

-   **Forgetting to convert map/filter results to list:** Use list() to convert iterables to lists.

#### Keywords

lambdamapfiltersortedhigher-order functionfunctional programming

[Learn more](https://docs.python.org/3/howto/functional.html)

#### Lambda functions and map()

Demonstrates lambda functions with map() for transformations.

Code

```
1squares = list(map(lambda x: x**2, [1, 2, 3, 4]))2print(squares)3
4add = lambda x, y: x + y5print(add(5, 3))
```

Execution

```
1python -c "squares = list(map(lambda x: x**2, [1, 2, 3, 4])); print(squares); add = lambda x, y: x + y; print(add(5, 3))"
```

Output

```
1[1, 4, 9, 16]28
```

-   lambda x: expression creates an anonymous function.
-   map() applies function to each element in a sequence.

#### filter() and sorted()

Shows filter() for selecting elements and sorted() with custom sort keys.

Code

```
1numbers = [1, 2, 3, 4, 5, 6]2evens = list(filter(lambda x: x % 2 == 0, numbers))3print(evens)4
5data = [(3, "c"), (1, "a"), (2, "b")]6sorted_data = sorted(data, key=lambda x: x[1])7print(sorted_data)
```

Execution

```
1python -c "numbers = [1, 2, 3, 4, 5, 6]; evens = list(filter(lambda x: x % 2 == 0, numbers)); print(evens); data = [(3, 'c'), (1, 'a'), (2, 'b')]; sorted_data = sorted(data, key=lambda x: x[1]); print(sorted_data)"
```

Output

```
1[2, 4, 6]2[(1, 'a'), (2, 'b'), (3, 'c')]
```

-   filter() keeps elements where the function returns True.
-   sorted(key=...) allows custom sorting with a function.

Was this useful?

## Tags

#Python#Programming#Scripting#Object Oriented#Functions#Classes#Variables#Data Types#Control Flow

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Python&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython&title=Python&summary=Python%20is%20an%20interpreted%2C%20high-level%20programming%20language%20known%20for%20its%20readability%20and%20simplicity.%20It%20supports%20multiple%20programming%20paradigms%20including%20procedural%2C%20object-oriented%2C%20and%20functional%20programming.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Python%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython&text=Python "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython&title=Python "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython&t=Python "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython&media=&description=Python%20is%20an%20interpreted%2C%20high-level%20programming%20language%20known%20for%20its%20readability%20and%20simplicity.%20It%20supports%20multiple%20programming%20paradigms%20including%20procedural%2C%20object-oriented%2C%20and%20functional%20programming. "Share on Pinterest")[Email](<mailto:?subject=Python&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fpython>)

## Comments

## You might also enjoy

More posts on similar topics

## [JavaScript](/cheatsheets/javascript)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Web Development
-   Frontend
-   Backend
-   Scripting

JavaScript is a high-level programming language that powers the web. It supports object-oriented, functional, and event-driven programming styles. The sections below cover JavaScript syntax and metho

#JavaScript#ES6#Web Development+3 tags

[read more](/cheatsheets/javascript)

## [Go](/cheatsheets/go)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Go
-   Systems Programming
-   Web Development
-   Backend
-   Concurrency

Go is a statically typed, compiled programming language designed with simplicity and efficiency in mind. It excels at concurrent programming, which makes it a good fit for fast, scalable server applic

#Go#Golang#Programming+6 tags

[read more](/cheatsheets/go)

## [Dart](/cheatsheets/dart)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Programming Language
-   Dart
-   Application Development
-   Type Safety
-   Null Safety

Dart is a statically-typed, strongly null-safe programming language designed for building fast, multi-platform applications. Created by Google, Dart ships with its own compiler, formatter, and package

#Dart#Programming#Type Safety+5 tags

[read more](/cheatsheets/dart)

## [Bash](/cheatsheets/bash)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Scripting
-   Shell
-   Linux
-   Unix
-   Command Line
-   Automation

Bash is a Unix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell. The sections below cover Bash commands, syntax, and examples.

#Scripting#Shell#Linux+3 tags

[read more](/cheatsheets/bash)

## [Python Virtual Environments Cheatsheet](/cheatsheets/python-venv)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Python
-   Development Tools
-   Dependency Management

A fast reference for keeping Python projects isolated and reproducible. It covers creating and activating environments with venv, installing packages with pip, locking dependencies with requirements f

#Python#Virtualenv#Pip+5 tags

[read more](/cheatsheets/python-venv)

## [AWK](/cheatsheets/awk)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Text Processing
-   Linux
-   Command Line
-   Development Tools
-   Scripting

AWK complete reference guide Quick start Print entire file awk '{ print }' file.txt# Print specific column awk '{ print $1 }' file.txt# Print lines matching pattern awk '/patter

#AWK#Text Processing#Pattern Matching+3 tags

[read more](/cheatsheets/awk)

6 related posts
