Fundamentals 9 min read

Discover Python’s New Built‑in Functions That Simplify Your Code

From Python 3.9 to 3.12 the standard library adds a suite of ready‑to‑use functions—such as str.removeprefix/removesuffix, math.dist, math.comb, zoneinfo, hashlib.blake2b, and tomllib—that eliminate repetitive code, boost performance, and let developers focus on core logic.

Data STUDIO
Data STUDIO
Data STUDIO
Discover Python’s New Built‑in Functions That Simplify Your Code

String handling

Python 3.9 introduced str.removeprefix() and str.removesuffix(), which remove a specified prefix or suffix only when present, otherwise returning the original string. This replaces manual startswith / endswith checks and slicing, making the intent explicit and the code safer.

# Old way
if filename.startswith("2023_"):
    clean_name = filename[5:]
print(clean_name)  # report_final.pdf

# New way
clean_name = filename.removeprefix("2023_")
print(clean_name)  # report_final.pdf

path = "project/utils.py"
print(path.removesuffix(".txt"))  # project/utils.py (no change)
print(path.removesuffix(".py"))   # project/utils

Math and statistics

Python 3.10+ expands the math module with math.dist() for Euclidean distance in any dimension, and math.comb() / math.perm() for fast combinatorial calculations. The statistics module adds correlation, covariance, and linear_regression, providing basic data‑analysis tools without external libraries.

import math
point_a = (1, 2, 3)
point_b = (4, 5, 6)
print(f"3‑D distance: {math.dist(point_a, point_b):.2f}")  # 5.20

print(f"C(5,3) = {math.comb(5, 3)}")   # 10
print(f"P(5,3) = {math.perm(5, 3)}")   # 60

import statistics
x = [1,2,3,4,5]
y = [2,4,5,4,5]
print(f"Correlation: {statistics.correlation(x, y):.3f}")   # 0.775
print(f"Covariance: {statistics.covariance(x, y):.3f}")   # 1.250
slope, intercept = statistics.linear_regression(x, y)
print(f"y = {slope:.2f}x + {intercept:.2f}")   # y = 0.70x + 1.70

System and time

Python 3.9 integrates the IANA time‑zone database via the zoneinfo module, replacing the third‑party pytz. It offers a modern, straightforward API for creating aware datetimes and converting between zones.

from datetime import datetime, timezone
from zoneinfo import ZoneInfo
beijing = datetime(2023,10,1,10,0, tzinfo=ZoneInfo("Asia/Shanghai"))
print(f"Beijing time: {beijing}")
ny = beijing.astimezone(ZoneInfo("America/New_York"))
print(f"New York time: {ny}")

Pure‑Python hashing (Python 3.11+)

The hashlib module now includes pure‑Python implementations of blake2b and blake2s, useful when C extensions are unavailable.

import hashlib
data = b"Hello, Modern Python!"
h = hashlib.blake2b(data, digest_size=32)
print(f"BLAKE2b hash: {h.hexdigest()}")

TOML configuration parsing (Python 3.11+)

Python 3.11 adds the tomllib module, enabling native parsing of TOML files such as pyproject.toml without external dependencies.

# config.toml
[database]
host = "localhost"
port = 5432
name = "mydb"

[server]
debug = true
allowed_hosts = ["127.0.0.1", "192.168.1.1"]

import tomllib
with open("config.toml", "rb") as f:
    cfg = tomllib.load(f)
print(f"DB host: {cfg['database']['host']}")
print(f"Debug mode: {cfg['server']['debug']}")
print(f"Allowed hosts: {cfg['server']['allowed_hosts']}")

Conclusion

Each release from Python 3.9 to 3.12 adds “out‑of‑the‑box” utilities that streamline common tasks, improve code robustness, and often outperform hand‑written equivalents. Leveraging these built‑in functions lets developers concentrate on business logic rather than reinventing well‑solved utilities.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonstatisticsbuilt-in functionshashlibtomllibzoneinfomath.diststr.removeprefix
Data STUDIO
Written by

Data STUDIO

Click to receive the "Python Study Handbook"; reply "benefit" in the chat to get it. Data STUDIO focuses on original data science articles, centered on Python, covering machine learning, data analysis, visualization, MySQL and other practical knowledge and project case studies.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.