str() is Python’s built-in function (and the foundation of all string conversion) that returns the human-readable string representation of any object — the same string you get when you do print(obj). It’s the preferred way to convert values to strings for display, logging, concatenation, formatting, and file output. In 2026, str() remains ubiquitous in data science (formatting pandas/Polars/Dask results, Series to strings), software engineering (logging, user messages, JSON serialization), and interactive tools — working on all types, falling back to __str__() (or __repr__() if not defined), and serving as the backbone for f-strings and format().
Here’s a complete, practical guide to using str() in Python: basic conversion, custom __str__, real-world patterns (earthquake report formatting, logging, display), and modern best practices with type hints, performance, safe conversion, and integration with pandas/Polars/Dask/f-strings/rich.
Basic str() usage — convert any object to its string form.
print(str(42)) # '42'
print(str(3.14159)) # '3.14159'
print(str(True)) # 'True'
print(str([1, 2, 3])) # '[1, 2, 3]'
print(str({'a': 1})) # "{'a': 1}"
print(str(None)) # 'None'
print(str(range(5))) # 'range(0, 5)'
Custom __str__ — control human-readable display (used by print()).
class Earthquake:
def __init__(self, mag, place, time):
self.mag = mag
self.place = place
self.time = time
def __str__(self):
return f"M{mag:.1f} - {place} ({time.date()})"
def __repr__(self):
return f"Earthquake(mag={self.mag}, place={self.place!r}, time={self.time!r})"
eq = Earthquake(7.2, "Japan", pd.Timestamp("2025-03-01"))
print(eq) # M7.2 - Japan (2025-03-01) ? __str__
print(repr(eq)) # Earthquake(mag=7.2, place='Japan', time=Timestamp('2025-03-01 00:00:00')) ? __repr__
print(f"Event: {eq}") # Event: M7.2 - Japan (2025-03-01)
Real-world pattern: formatted earthquake reporting & display — str() for clean output.
import pandas as pd
df = pd.read_csv('earthquakes.csv')
# Basic string conversion
df['mag_str'] = df['mag'].apply(str) # '7.2', '6.8', etc.
print(df['mag_str'].head())
# Custom formatted strings
def event_str(row):
return f"{row['time']:%Y-%m-%d} | Mag {row['mag']:.1f} | {row['place']}"
df['report'] = df.apply(event_str, axis=1)
print(df['report'].head())
# Polars: string conversion
import polars as pl
pl_df = pl.from_pandas(df)
pl_df = pl_df.with_columns(pl.col('mag').cast(pl.String).alias('mag_str'))
print(pl_df['mag_str'].head())
Best practices for str() in Python & data workflows. Prefer f-strings — f"Mag {mag:.1f}" — for formatting; use str() for simple conversion. Modern tip: use Polars pl.col('x').cast(pl.String) — fast columnar str(); Dask ddf['x'].astype(str). Use str(obj) — when you need string for concatenation/file output. Add type hints — def format_event(obj: Any) -> str: return str(obj). Prefer __str__ — for user-facing display; __repr__ for debugging. Use str() in logging — logger.info(str(df.head())). Use str() in assertions — assert str(value) == "expected". Use str.join() — "\n".join(map(str, lst)) for clean output. Use str.format() — legacy but still useful: "Mag {:.1f}".format(mag). Use str() with bytes — str(b'hello', 'utf-8'). Use str.encode() — reverse to bytes. Use str.lower()/upper()/title() — case conversion. Use str.strip() — remove whitespace. Use str.replace() — string substitution. Use str.split() — to list. Use str.join() — from list to string. Use str.isdigit() — numeric check. Use str.isalpha() — letter check. Use str.startswith()/endswith() — prefix/suffix. Use str.find()/index() — substring search. Use str.count() — occurrence count. Use str.format_map() — with dict. Use str.maketrans() — translation table. Use str.translate() — apply translation. Use str.center()/ljust()/rjust() — alignment. Use str.zfill() — zero padding. Use str.casefold() — aggressive lower for comparisons. Use str.removeprefix()/removesuffix() — Python 3.9+.
str(obj) converts any object to its string representation — used for display, logging, concatenation, and file output, customizable via __str__. In 2026, prefer f-strings for dynamic formatting, str() for simple conversion, and integrate with pandas/Polars/Dask for column string casting. Master str(), and you’ll handle text representation cleanly and efficiently in any Python workflow.
Next time you need to turn something into a string — use str(). It’s Python’s cleanest way to say: “Give me the readable text version of this object — ready to print or concatenate.”