Python 中的 expandtabs() 函数有助于将字符串中的 '\t' 字符替换为空格。该函数允许指定所需的空格量。最后,返回修改后的字符串作为输出。
string.expandtabs(tabsize) #where tabsize is an integer value
expandtabs() 函数接受一个参数。如果需要替换多个制表符,则只有当它到达前一个制表符时,才会计算制表符之前的字符。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| tabsize | 指定制表符大小的数字。默认制表符大小为 8。 | 可选 |
返回值为字符串。它返回原始字符串在用空格扩展后的副本。
| 输入 | 返回值 |
|---|---|
| 字符串 | 带空格的字符串 |
string = 'abc\t56789\tefg'
# no argument is passed
# default tabsize is 8
result = string.expandtabs()
print(result)
输出
abc 56789 efg
string = "abc\t56789\tdef"
print('Original String:', str)
# tabsize is set to 2
print('Expanded tabsize 2:', string.expandtabs(2))
# tabsize is set to 3
print('Expanded tabsize 3:', string.expandtabs(3))
# tabsize is set to 4
print('Expanded tabsize 4:', string.expandtabs(4))
# tabsize is set to 5
print('Expanded tabsize 5:', string.expandtabs(5))
# tabsize is set to 6
print('Expanded tabsize 6:', string.expandtabs(6))
输出
Original String: abc 56789 def Expanded tabsize 2: abc 56789 def Expanded tabsize 3: abc 56789 def Expanded tabsize 4: abc 56789 def Expanded tabsize 5: abc 56789 def Expanded tabsize 6: abc 56789 def