Python3 expandtabs() Method
Description
The expandtabs() method converts tab symbols in the string\tinto spaces. The tab symbol\tdefaults to 8 spaces, with tab stops at positions 0, 8, 16, etc. If the number of characters from the current position to the start or the previous tab stop is not a multiple of 8, spaces are used instead.
Syntax
expandtabs() method syntax:
str.expandtabs(tabsize=8)
Parameters
- tabsize -- Specifies the tab symbol in the string to be converted\tinto the number of spaces.
Return Value
This method returns the tab symbols in the string\tconverted to spaces as a new string.
Example
The following example demonstrates the expandtabs() method:
Example
#!/usr/bin/python3
str = "example\t12345\tabc"
print('Original string:', str)
# Default 8 spaces
# runnob has 6 characters, the following \t fills 2 spaces
# 12345 has 5 characters, the following \t fills 3 spaces
print('Replace\\tab symbol:', str.expandtabs())
# 2 spaces
# runnob has 6 characters, exactly 3 times 2, the following \t fills 2 spaces
# 12345 has 5 characters, not a multiple of 2, the following \t fills 1 space
print('Replace with 2 spaces\\tab symbol:', str.expandtabs(2))
# 3 spaces
print('Using 3 spaces:', str.expandtabs(3))
# 4 spaces
print('Using 4 spaces:', str.expandtabs(4))
# 5 spaces
print('Using 5 spaces:', str.expandtabs(5))
# 6 spaces
print('Using 6 spaces:', str.expandtabs(6))
The output of the above example is as follows:
原始字符串: example 12345 abc 替换 \t 符号: example 12345 abc 使用 2 个空格替换 \t 符号: example 12345 abc 使用 3 个空格: example 12345 abc 使用 4 个空格: example 12345 abc 使用 5 个空格: example 12345 abc 使用 6 个空格: example 12345 abc
Other Extensions
Python3 Strings