Convert strings to integers using int() with error handling for invalid input.
Cookbooks
Cookbooks
Practical recipes for real-world Python programming tasks.
- How to Convert a String to an Integer in Python
- How to Join a List into a String in Python
Learn how to convert a list to a string in Python using str.join, with examples for strings, numbers, custom separators, and edge cases.
- How to count occurrences of an item in a list in Python
Count how many times an element appears in a list using list.count(), Counter, or a manual loop.
- How to Generate a Random Number in Python
Generate random numbers using the random module — integers, floats, and within ranges.
- How to find the maximum value in a list in Python
Find the maximum value in a list using max(), sorted(), or a loop. Includes handling empty lists and custom objects.
- How to flatten a nested list in Python
Flatten a nested list using list comprehension, itertools, or recursion.
- How to read a file line by line in Python
Read a file line by line using for loops, readlines(), or iter(). Compare memory efficiency and use cases.
- How to merge two dictionaries in Python
Merge dictionaries using the | operator, ** unpacking, or .update(). The | operator is the cleanest for Python 3.9+.
- How to get the current date and time in Python
Get the current date and time using datetime.now() or timezone-aware datetime with zoneinfo. Also covers date only and time only.
- How to check if a key exists in a dictionary in Python
Check if a dictionary key exists using in, .get(), or catching KeyError. The in operator is the most Pythonic.
- How to remove duplicates from a list in Python
Remove duplicates while preserving order using dict.fromkeys() or a loop. The simplest solution is list(dict.fromkeys(items)).
- How to reverse a string in Python
Reverse a string using slicing or reversed(). The fastest method is slicing with [::-1].
- How to write to a file in Python
Write text or binary data to files using Python built-in open function with different modes.
- How to Swap Two Variables in Python
Swap two variables in Python using tuple unpacking or a temporary variable. Tuple unpacking is the most Pythonic way.
- How to sort a list by a key in Python
Sort lists by custom criteria using the key parameter in sorted() and list.sort().
- How to total a CSV column with csv.DictReader
Read a CSV file with csv.DictReader and total one column in Python with a simple loop.