更新时间:2023-10-03 13:58:43
既然你想要一个不使用任何外部模块的python函数,我认为你应该首先设计你函数的算法......
Since you wan't a python function that doesn't use any external module, I think you should design first the algorithm of your function...
我建议迭代字符串的每个字符;如果 char i 是制表符,则需要计算要插入多少个空格:下一个对齐"索引是 ((i/tabstop) + 1) * tabstop.所以你需要插入 ((i/tabstop) + 1) * tabstop - (i % tabstop).但更简单的方法是插入制表符直到对齐(即 i % tabstop == 0)
I would propose to iterate on every char of the string ; if char i is a tab, you need to compute how many spaces to insert : the next "aligned" index is ((i / tabstop) + 1) * tabstop. So you need to insert ((i / tabstop) + 1) * tabstop - (i % tabstop). But an easier way is to insert tabs until you are aligned (i.e. i % tabstop == 0)
def replace_tab(s, tabstop = 4):
result = str()
for c in s:
if c == '\t':
while (len(result) % tabstop != 0):
result += ' ';
else:
result += c
return result