Skip to content

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:

Python
>>> 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() returns True if the string contains only whitespace
Python
>>> "  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:

Python
>>> 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.

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.

basics best-practices python

For additional information on related topics, take a look at the following resources:


By Dan Bader • Updated March 21, 2026