Python string expandtabs explanation with example

Python string expandtabs method:

expandtabs method is used to change the tabs to whitespaces in a string. In this post, we will learn how to use expandtabs with examples.

Definition of expandtabs:

expandtabs is defined as below:

string.expandtabs(size)

Here, size is optional value. It is a number that defines the tabsize or number of whitespaces to replace with tabs in the string. If we don’t provide this value, it will be 8. It returns the new string.

Example of expandtabs:

Let’s take a look at the below program:

given_string = 'hello\tworld\t!!'
print('Original string: {}'.format(given_string))

modified_string = given_string.expandtabs(2)
print('Modified string: {}'.format(modified_string))

If you run this program, it will print the below output:

Original string: hello  world   !!
Modified string: hello world !!

Here, given_string is the given string. We used expandtabs method to replace all tabs with two whitespaces and stored the value in the variable modified_string. The modified string has tabs replaced by two whitespaces.

expandtabs without any value:

If we don’t provide any value to expandtabs, it will be 8 whitespaces. For example:

given_string = 'hello\tworld\t!!'
print('Original string: {}'.format(given_string))

modified_string = given_string.expandtabs()
print('Modified string: {}'.format(modified_string))

It will print:

Original string: hello  world   !!
Modified string: hello   world   !!

expandtabs with negative value:

If we pass a negative value to this method, it removes all tabs in that string. For example:

given_string = 'hello\tworld\t!!'
print('Original string: {}'.format(given_string))

modified_string = given_string.expandtabs(-10)
print('Modified string: {}'.format(modified_string))

It will print :

Original string: hello  world   !!
Modified string: helloworld!!

Errors:

expandtabs takes only an integer value. It will throw a typeerror if we pass any value other than integer.

For example:

given_string = 'hello\tworld\t!!'
print('Original string: {}'.format(given_string))

modified_string = given_string.expandtabs(1.2)
print('Modified string: {}'.format(modified_string))

It will throw:

TypeError: integer argument expected, got float