Expand Tabs in String to Multiple Spaces in Python



In Python, handling white spaces between strings is easy. Sometimes, we may want to add space in a string, but we are not sure exactly how much. Python provides different ways to manage this, and one useful method is expandtabs() method.

Using the expandtabs() Method

The expandtabs() method in Python is used to replace tab characters (\t) in a string with spaces. It returns a new string where each \t is replaced with the number of spaces needed to reach the next tab stop.

You can control how many spaces are used by passing a tabsize value to the method. This is helpful when you want consistent spacing in strings, especially when working with formatted text. Manually adjusting tabs can be difficult, so using expandtabs() makes it easier to manage spacing automatically.

Syntax

Following is the syntax of the expandtabs() method -

string.expandtabs(size_of_tab)

where, size_of_tab_ is the number of spaces used to replace each \t (tab) character. By default, it is set to 8.

Return value

The method returns a new string where each \t character is replaced with spaces up to the next multiple of the specified tab size.

Example: Without any Parameter

In the following example, we do not pass any parameters to the expandtabs() method -

string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = string.expandtabs()
print('The expanded string is:', result)

The expandtabs() method is used here without a parameter (i.e., the tab size). As a result, the default tab size of 8 is applied to replace the \t characters with spaces -

The expanded string is: Expanding       tabs    in      string  to      multiple        spaces.

Example: With Different Parameters

In the following example, we pass different parameters to the expandtabs() method -

string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = string.expandtabs(6)
result1 = string.expandtabs(3)
result2 = string.expandtabs(2)
print('The expanded string is:', result)
print('The expanded string is:', result1)
print('The expanded string is:', result2)

Size = 6, Size = 3, and Size = 2 are passed as parameters to the Python string expandtabs() method in the above code. As a result, spaces of sizes 6, 3, and 2 units respectively are used to replace the \t character in the entire string -

The expanded string is: Expanding   tabs  in    string      to    multiple    spaces.
The expanded string is: Expanding   tabs  in string   to multiple spaces.
The expanded string is: Expanding tabs  in  string  to  multiple  spaces.

Errors and Exceptions in expandtabs() Function

The Python string expandtabs() method raises a TypeError exception if you pass a non-integer value, such as a floating-point number, as a parameter. This indicates that the expandtabs() function only accepts integer values as a parameter.

Example

Below is an example where a non-integer value is passed to the expandtabs() method -

string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = string.expandtabs(6.2)
print('The expanded string is:', result)

The following error occurs when executing the above code -

Traceback (most recent call last):
  File "/home/cg/root/6818cec0b940d/main.py", line 2, in <module>
result = string.expandtabs(6.2)
             ^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'float' object cannot be interpreted as an integer

Using numpy.expandtabs() Function

The numpy.char.expandtabs() function in the Python NumPy module performs the same task as the built-in expandtabs() function. If you want to be more exact, you can pass an array as an argument to the numpy.char.expandtabs() function, along with the size of the spaces.

Syntax

The syntax for numpy.expandtabs() is as follows -

numpy.char.expandtabs(array, size_of_tab)

Where,

  • array contains the elements that the function operates on.
  • size_of_tab (optional) specifies the number of spaces used to replace the tab character (\t). This is an optional parameter.

Example

Below is an example of using numpy.expandtabs() function -

import numpy
given_array = numpy.array("Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces.")
result = numpy.char.expandtabs(given_array, 16)
print('The expanded string array is:', result)

The output of the above code is -

The expanded string array is: Expanding       tabs            in              string          to              multiple        spaces.

Using replace() Method

The replace() method in Python's string class is used to replace one substring with another. It takes two string arguments: the substring to be replaced and the new substring to insert. This method is used with string objects.

Example

The following example demonstrates how to replace tab characters in a string using the replace() method -

string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = string.replace('\t', ' ')
print(result)

The output of the above code is -

Expanding tabs in string to multiple spaces.

Using "re" Module

You can also use regular expressions with Python's built-in re module to achieve the same result. The re.sub() function is used to replace parts of a string using the following syntax -

re.sub(pattern_to_replace, replacement_string, original_string)

Example

The example below shows how to replace tab characters in a string using the re module -

import re
string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = re.sub('\t', ' ', string)
print(result)

The output of the above code is -

Expanding tabs in string to multiple spaces.
Updated on: 2025-05-07T13:13:17+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements