str.expandtabs()

str.expandtabs(tabsize=8)
Returns: str · Updated March 13, 2026 · String Methods
strings whitespace formatting

The expandtabs() method returns a copy of the string where all tab characters are replaced by spaces. This is useful when working with text that contains tabs and you need consistent spacing across different environments.

Syntax

str.expandtabs(tabsize=8)

Parameters

  • tabsize (int, optional): The number of spaces to replace each tab with. Defaults to 8.

Returns: A new string with tabs expanded to spaces.

Examples

Basic usage

text = "hello\tworld"
print(text.expandtabs())
# hello       world

The single tab character is replaced with 8 spaces by default.

Custom tab size

# Use 4 spaces per tab
text = "name\tage\tcity"
print(text.expandtabs(4))
# name    age    city

# Use 2 spaces per tab
print(text.expandtabs(2))
# name  age  city

You can customize the tab size to match your formatting needs.

Mixed tabs and spaces

text = "a\tb\tc"
print(f'Default (8): "{text.expandtabs()}"')
print(f'Tab size 4: "{text.expandtabs(4)}"')
print(f'Tab size 2: "{text.expandtabs(2)}"')
# Default (8): "a       b       c"
# Tab size 4: "a   b   c"
# Tab size 2: "a  b  c"

Common Patterns

Reading tab-delimited data

# Simulating tab-delimited text
line = "John\t30\tLondon"
fields = line.expandtabs(4).split()
print(fields)
# ['John', '30', 'London']

Preparing text for display

def format_columns(data, col_width=8):
    """Format data into columns using expandtabs."""
    return '\n'.join(
        '\t'.join(str(item).ljust(col_width) for item in row)
        for row in data
    )

data = [["Name", "Age"], ["Alice", "30"], ["Bob", "25"]]
print(format_columns(data))
# Name      Age     
# Alice     30      
# Bob       25      

Converting tabs to spaces in files

def convert_tabs_to_spaces(content, spaces=4):
    """Replace tabs with spaces in text content."""
    return content.expandtabs(spaces)

# Example
with open('input.txt', 'r') as f:
    content = f.read()
    
converted = convert_tabs_to_spaces(content)
# Process the converted content

Edge Cases

Empty strings

print("".expandtabs())
# (empty string)

Strings without tabs

print("hello world".expandtabs())
# hello world

Tab at end of string

print("hello\t".expandtabs())
# hello       

Multiple consecutive tabs

print("a\t\tb".expandtabs())
# a               b

Two tabs become 16 spaces (8 + 8).

See Also