Python 3 – String expandtabs() Method
If you want to insert a tab inside a string, usually you use the \t character. However, the number of spaces represented by a tab can vary depending on the software or operating system being used. The expandtabs()
method in Python helps to solve this problem, allowing you to specify the number of spaces to be replaced by a tab.
Syntax
The syntax for using the expandtabs()
method is as follows:
str.expandtabs(tabsize)
Here, str
is the string on which expandtabs()
is to be applied, and tabsize
is an optional parameter specifying the number of spaces to be replaced by each tab. If you don’t specify a value for tabsize
, it defaults to 8.
The expandtabs()
method returns a new string with each tab
character replaced by a number of whitespace characters which is determined by tabsize
.
Examples
Here are some examples to help you better understand how to use the expandtabs()
method:
Example 1: Basic Usage
str1 = "Hello\tWorld"
str2 = "Hellooooo\tWorld"
str3 = "Hellooo\tWorld"
print(str1.expandtabs())
print(str2.expandtabs())
print(str3.expandtabs())
Output:
Hello World
Hellooooo World
Hellooo World
Here, we are using the expandtabs()
method on different strings by default size. The str1
has the tab character with a single tab space, str2
has the tab character with a size of 7 and str3
has the tab character with a size of 5. The output shows that the tab character is replaced by the number of required spaces specified by tabsize
.
Example 2: Specifying Tabsize
str1 = "Hello\tWorld"
str2 = "Hellooooo\tWorld"
str3 = "Hellooo\tWorld"
print(str1.expandtabs(4))
print(str2.expandtabs(2))
print(str3.expandtabs(10))
Output:
Hello World
Hellooooo World
Hellooo World
In this example, we have passed different tabsize values (4,2,10) to method expandtabs()
. The output shows us that the number of spaces required for each tab is determined by the value of tabsize
.
Conclusion
The expandtabs()
method helps to replace tabs with white spaces according to a defined number of spaces by specifying tabsize
parameter. This method is used to prevent the misalignment of text caused by changes in the number of spaces represented by a tab.
In summary, it is a simple and useful method for formatting strings in Python programming.