Mastering Python Essentials: Variable Swapping, F-Strings, Formatting, and Slice Notation

Swapping Variable Values

Python provides elegant ways to exchange values between variables. simplest approach uses tuple unpacking, which works for any number of variables as long as both sides of the assignment have the same count.

x_val = 11
y_val = 7

x_val, y_val = y_val, x_val

print(x_val)  # 7
print(y_val)  # 11

Arithmetic Swap (Numbers Only)

For numeric variables, you can also swap values using arithmetic operations like addition/subtraction or multiplication/division. This method calculates a temporary sum or product to rearrange the values.

m = 11
n = 7

m = m + n   # m = 18, n = 7
n = m - n   # m = 18, n = 11
m = m - n   # m = 7, n = 11

print(m)  # 7
print(n)  # 11

Six Powerful F-String Techniques

Python’s f-strings offer a readable, concise, and error-resistant way to format strings compared to older methods. Here are some practical techniques.

Basic String Interpolation

Insert variable values directly by wrapping them in curly braces {}.

item_name = 'apples'
quantity = 42

print(f'{quantity} {item_name}')  # 42 apples

Displaying Variable Names

During debugging, it’s helpful to show both the variable name and its value. Append an equals sign = inside the braces to enable this.

item_name = 'apples'
quantity = 42

print(f'{item_name=}, {quantity = }')  # item_name='apples', quantity = 42

Inline Mathematical Expressions

Place mathematical expressions inside f-strings. Adding = after the expression prints both the expression and the result.

total = 42

print(f'{total % 2 = }')  # total % 2 = 0

Printable Representation

To obtain a string’s printable representation (similar to repr()), use the !r conversion flag.

label = 'apples'

print(f'{label!r}')  # 'apples'

Number Formatting

Apply format specifiers after a colon : to control numeric output. For example, .2f limits floating-point numbers to two decimal places.

unit_price = 6.12658

print(f'{unit_price:.2f}')  # 6.13

Date Formatting

Dates work with format specifiers as well. Use %Y for the full year, %m for the month, and %d for the day.

from datetime import datetime

current_time = datetime.utcnow()

print(f'{current_time=:%Y-%m-%d}')  # current_time=2021-07-09

Two Ways to Format Strings in Python

F-Strings (Formatted String Literals)

F-strings are prefixed with f or F and support replacement fields enclosed in curly braces.

username = 'John'
age = 32

print(f'{username} is {age} years old')  # 'John is 32 years old'

The str.format() Method

This method works similarly to f-strings, but the replacement fields are supplied as arguments rather than beinng embedded inside the string.

name = 'John'
years = 32

print('{0} is {1} years old'.format(name, years))  # 'John is 32 years old'

Understanding Python Slice Assignment and Notation

Basic Slice Syntax

Python’s slice notation extracts portions of a sequence using the pattern:

[start_at:stop_before:step]
  • start_at: index of the first item to include (inclusive, defaults to 0)
  • stop_before: index before which to stop (exclusive, defaults to length of sequence)
  • step: stride between items (defaults to 1)
digits = [1, 2, 3, 4, 5]

digits[1:4]    # [2, 3, 4]    start at 1, stop before 4
digits[2:]     # [3, 4, 5]    start at 2, go to the end
digits[:3]     # [1, 2, 3]    start at beginning, stop before 3
digits[1:4:2]  # [2, 4]       start at 1, stop before 4, step 2
digits[2::2]   # [3, 5]       start at 2, go to the end, step 2
digits[:3:2]   # [1, 3]       start at beginning, stop before 3, step 2
digits[::2]    # [1, 3, 5]    from beginning to end, step 2
digits[::]     # [1, 2, 3, 4, 5]  full shallow copy

A common idiom for shallow-copying a list is list_copy = original[:].

Negative Indices and Steps

Negative start_at and stop_before values count from the end of the list. A negative step reverses the slice direction, which requires start_at to be greater than stop_before.

values = [1, 2, 3, 4, 5]

values[1:-2]     # [2, 3]         start at 1, stop before the second-to-last
values[-3:-1]    # [3, 4]         start at third-to-last, stop before last
values[::-1]     # [5, 4, 3, 2, 1]  fully reversed
values[4:1:-1]   # [5, 4, 3]      reversed, start at 4, stop after 1
values[-1:1:-2]  # [5, 3]         reversed, start at last, stop after 1, step 2

Understanding these slice operations forms the foundation for efficient data manipulation in Python.

Tags: python f-strings variable swapping slice notation String Formatting

Posted on Wed, 30 Sep 2026 16:49:23 +0000 by climbjm