python 中的expandtabs()
函數有助于將字符串中的' \t '字符替換為空格。該函數允許指定所需的空間量。最后,修改后的字符串作為輸出返回。
**string.expandtabs(tabsize)** #where tabsize is an integer value
expandtabs()
參數:
expandtabs()
函數接受一個參數。如果我們需要替換多個制表符,那么制表符之前的字符只有在到達前一個制表符時才被計數。
參數 | 描述 | 必需/可選 |
---|---|---|
tabsize | 指定 tabsize 的數字。默認 tabsize 為 8 | 可選擇的 |
expandtabs()
返回值
返回值始終是字符串。它返回使用空格擴展后的原始字符串的副本。
| 投入 | 返回值 | | 線 | 帶有空格的字符串 |
Python 中expandtabs()
方法的示例
示例 1:如何在沒有參數的情況下使用expandtabs()
?
string = 'abc\t56789\tefg'
# no argument is passed
# default tabsize is 8
result = string.expandtabs()
print(result)
輸出:
abc 56789 efg
示例 2:如何用不同的參數擴展?
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