Python expandtabs() method
Description
The expandtabs() method converts tab symbols in a string into spaces. By default a tab symbol stands for 8 spaces, with tab stops at positions 0, 8, 16, and so on; if the number of characters from the start or from 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 number of spaces to replace the tab character ('\t') in the string with.
Return Value
This method returns a new string in which the tab characters ('\t') in the string have been replaced with spaces.
Example
The following example shows how to use the expandtabs() method:
Example
#!/usr/bin/python
-- coding: UTF-8 --
str
=
"runoob\t12345\tabc"
(
'Original string: {}'
.
format
(
str
)
)
Default 8 spaces
runnob has 6 characters, so the following tab is filled with 2 spaces
12345 has 5 characters, so the following tab is filled with 3 spaces
(
'Replace \t symbol: {}'
.
format
(
str
.
expandtabs
(
)
)
)
2 spaces
runnob has 6 characters, exactly 3 times 2, so the following tab is filled with 2 spaces
12345 has 5 characters, not a multiple of 2, so the following tab is filled with 1 space
(
'Replace \t symbol with 2 spaces: {}'
.
format
(
str
.
expandtabs
(
2
)
)
)
3 spaces
(
'Use 3 spaces: {}'
.
format
(
str
.
expandtabs
(
3
)
)
)
4 spaces
(
'Use 4 spaces: {}'
.
format
(
str
.
expandtabs
(
4
)
)
)
5 spaces
(
'Use 5 spaces: {}'
.
format
(
str
.
expandtabs
(
5
)
)
)
6 spaces
(
'Use 6 spaces: {}'
.
format
(
str
.
expandtabs
(
6
)
)
)
The output of the above example is:
原始字符串: runoob 12345 abc
替换 \t 符号: runoob 12345 abc
使用 2 个空格替换 \t 符号: runoob 12345 abc
使用 3 个空格: runoob 12345 abc
使用 4 个空格: runoob 12345 abc
使用 5 个空格: runoob 12345 abc
使用 6 个空格: runoob 12345 abc
Python Strings