Python3 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
Syntax of the expandtabs() method:
str.expandtabs(tabsize=8)
Parameters
- tabsize -- specifies how many characters a tab symbol in the string is converted into.
Return Value
This method returns the new string generated after converting tab symbols in the string into spaces.
Example
The following example demonstrates the expandtabs() method:
Example
#!/usr/bin/python3
str
=
"
runoob
\t
12345
\t
abc
"
(
'
Original string:
'
,
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
(
'
Replacement
\
t symbol:
'
,
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 with 2 spaces
\
t symbol:
'
,
str
.
expandtabs
(
2
)
)
3 spaces
(
'
Use 3 spaces:
'
,
str
.
expandtabs
(
3
)
)
4 spaces
(
'
Use 4 spaces:
'
,
str
.
expandtabs
(
4
)
)
5 spaces
(
'
Use 5 spaces:
'
,
str
.
expandtabs
(
5
)
)
6 spaces
(
'
Use 6 spaces:
'
,
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
Python3 Strings