Python expandtabs() Method

Python 字符串Python Strings


Description

The expandtabs() method converts tab symbols in the string\tinto spaces. Tab symbols\tThe default number of spaces is 8, and tab stop positions are at 0, 8, 16, etc. If the number of characters from the current position to the start position 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 number of spaces to convert tab symbols ('\t') in the string to.

Return Value

This method returns a new string created by converting tab symbols ('\t') in the string to spaces.

Example

The following example demonstrates the expandtabs() method:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

str = "example\t12345\tabc"
print('Original string: {}'.format(str))

# Default 8 spaces
# runnob has 6 characters, so the following \t is padded with 2 spaces
# 12345 has 5 characters, so the following \t is padded with 3 spaces
print('Replace\\t symbol: {}'.format(str.expandtabs()))

# 2 spaces
# runnob has 6 characters, exactly 3 times 2, so the following \t is padded with 2 spaces
# 12345 has 5 characters, not a multiple of 2, so the following \t is padded with 1 space
print('Using 2 spaces to replace\\t symbol: {}'.format(str.expandtabs(2)))

# 3 spaces
print('Using 3 spaces: {}'.format(str.expandtabs(3)))

# 4 spaces
print('Using 4 spaces: {}'.format(str.expandtabs(4)))

# 5 spaces
print('Using 5 spaces: {}'.format(str.expandtabs(5)))

# 6 spaces
print('Using 6 spaces: {}'.format(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

Python 字符串Python Strings

Other Extensions