Essential Python Techniques: Aliases, Variable Swapping, and String Formatting
Configuring Python Aliases
In various Linux or macOS environments, the default python command might refer to an older version. To ensure python and pip point to Python 3, aliases can be added to shell configuration files.
For Bash users, append the following to ~/.bashrc:
alias python='/usr/bin/python3'
alias pip='/usr/bin/pip3'
For Zsh users, add these lines to ~/.zshrc:
alias python='/usr/bin/python3'
alias pip='/usr/bin/pip3'
Restart the terminal or source the file to apply changes.
Techniques for Swapping Variables
Exchanging values between two variables is a common task. Python offers several approaches to achieve this.
Using a Temporary Holder
The traditional approach involves a third variable to hold data during the swap.
x = 10
y = 20
holder = x
x = y
y = holder
print(f"x: {x}, y: {y}")
Tuple Unpacking
Python supports a concise syntax for swapping without an intermediate variable by leveraging tuple packing and unpacking.
x = 10
y = 20
x, y = y, x
print(f"x: {x}, y: {y}")
Arithmetic Operations
For numeric values, arithmetic can be used to swap values in place, though this is less common due to potential overflow risks in other languages and readability concerns.
x = 10
y = 20
x = x + y
y = x - y
x = x - y
print(f"x: {x}, y: {y}")
Advanced F-String Formatting
F-strings provide a robust way to embed expressions inside string literals.
Interpolation and Debugging
Variables can be inserted directly. Adding an equals sign = prints the variable name alongside its value, which is excellent for debugging.
status = "active"
count = 42
print(f"Status: {status}")
print(f"{count=}")
Inline Calculations
Mathematical expressions can be evaluated within the curly braces.
total = 100
print(f"Half is {total / 2}")
print(f"{total % 3 = }")
Representation and Formatting
The !r conversion flag calls repr() on the value. Format specifiers allow control over precision.
label = "data"
amount = 12.34567
print(f"Label: {label!r}")
print(f"Amount: {amount:.2f}")
Date Formatting
Datetime objects can be formatted directly within the f-string using format codes.
import datetime
current_time = datetime.datetime.now()
print(f"Today: {current_time:%Y-%m-%d}")
String Formatting Approaches
Aside from f-strings, Python supports the format() method.
F-Strings
username = "Alice"
score = 95
print(f"{username} scored {score}")
The format() Method
This method uses positional or keyword arguments.
username = "Alice"
score = 95
print("{} scored {}".format(username, score))
Understanding Slice Notation
Slicing allows extracting a portion of a sequence. The syntax is [start:stop:step].
start: The index where the slice begins (inclusive).stop: The index where the slice ends (exclusive).step: The interval between elements.
numbers = [0, 1, 2, 3, 4, 5]
# Elements from index 1 up to 4
subset = numbers[1:4] # Result: [1, 2, 3]
# Elements from index 2 to the end
tail = numbers[2:] # Result: [2, 3, 4, 5]
# Elements from the beginning up to index 3
head = numbers[:3] # Result: [0, 1, 2]