str.expandtabs(n) 跟踪每行上的当前光标位置,并将其找到的每个制表符字符替换为当前光标位置到下一个制表位的空格数。
str.expandtabs(n) 不等于 str.replace("\t", " " * n)
string.expandtabs(n) 相当于:
def expandtabs(string, n):
result = ""
pos = 0
for char in string:
if char == "\t":
# 替代 tab 字符, append the
# 添加指定数量代空格数到下一个 tab 字符
char = " " * (n - pos % n)
if char == "\n":
pos = 0
else:
pos += len(char)
result += char
return result
使用例子
input = "123\t12345\t1234\t1\n12\t1234\t123\t1"
print(expandtabs(input, 10))
疑问例子
str = "this is\tstring"
for i in range(10):
print(str.expandtabs(i).replace(' ', "*"), i)
空格数为一个制表符大小减去已有的字符
this*isstring 0
this*is*string 1
制表符大小为1
t|h|i|s| |i|s| |s|t|r|i|n|g|
this*is*string 2
th|is| i|s |st|ri|ng|
this*is**string 3
thi|s i|s |str|ing|
this*is*string 4
this| is |stri|ng
this*is***string 5
this*is*****string 6
this*is*******string 7
this is| |stinrg
this*is*string 8
制表符大小为8
this is |string
this*is**string 9
renmu
renmu
110***2351@qq.com3年前 (2017-10-25)