whitespace
In Python, whitespace refers to characters that represent horizontal or vertical space in text. The most common whitespace characters are spaces, tabs (\t), and newlines (\n).
Notably, Python uses whitespace for indentation, which defines the structure of code blocks instead of curly braces or keywords.
Whitespace plays two distinct roles in Python. At the beginning of a line, it determines indentation levels and defines code blocks for loops, functions, classes, and conditional statements. Between tokens, it separates identifiers and operators when needed. Python’s reliance on significant whitespace is one of its most distinctive features and helps enforce readable, consistently formatted code.
Whitespace Characters
Python recognizes several ASCII whitespace characters:
- Space (
) – The most common whitespace character - Tab (
\t) – A horizontal tab - Newline (
\n) – A line feed that ends a line - Carriage return (
\r) – Used in Windows-style line endings (\r\n) - Form feed (
\f) – A page break character - Vertical tab (
\v) – A vertical spacing character
You can access all of these through the string.whitespace constant:
>>> import string
>>> string.whitespace
' \t\n\r\x0b\x0c'
Working With Whitespace in Strings
Several built-in string methods handle whitespace by default when called without arguments:
.strip()removes leading and trailing whitespace.split()splits on any whitespace and ignores extra spaces.isspace()returnsTrueif the string contains only whitespace
>>> " hello world ".strip()
'hello world'
>>> " hello world ".split()
['hello', 'world']
>>> " \t\n".isspace()
True
Example
Here is a quick example showing how Python uses whitespace for indentation and how you can detect whitespace characters in strings:
>>> def greet(name):
... if name.strip():
... print(f"Hello, {name.strip()}!")
... else:
... print("Name is empty or only whitespace.")
...
>>> greet(" Alice ")
Hello, Alice!
>>> greet(" ")
Name is empty or only whitespace.
In this example, .strip() removes the surrounding whitespace from the input string. The if block uses the truthiness of the stripped string to check whether the name contains any non-whitespace characters.
Related Resources
Tutorial
How to Properly Indent Python Code
Learn how to properly indent Python code in IDEs, Python-aware editors, and plain text editors—plus explore PEP 8 formatters like Black and Ruff.
For additional information on related topics, take a look at the following resources:
- How to Strip Characters From a Python String (Tutorial)
- Strings and Character Data in Python (Tutorial)
- How to Split a String in Python (Tutorial)
- How to Properly Indent Python Code (Quiz)
- Strip Characters From a Python String (Course)
- How to Strip Characters From a Python String (Quiz)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)
- Python String Splitting (Course)
- How to Split a String in Python (Quiz)
By Dan Bader • Updated March 21, 2026