Python expandtabs()方法
描述
Python expandtabs() 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。
语法
expandtabs()方法语法:
str.expandtabs(tabsize=8)
参数
- tabsize -- 指定转换字符串中的 tab 符号('\t')转为空格的字符数。
返回值
该方法返回字符串中的 tab 符号('\t')转为空格后生成的新字符串。
实例
以下实例展示了expandtabs()方法的实例:
#!/usr/bin/python str = "this is\tstring example....wow!!!"; print "Original string: " + str; print "Defualt exapanded tab: " + str.expandtabs(); print "Double exapanded tab: " + str.expandtabs(16);
以上实例输出结果如下:
Original string: this is string example....wow!!! Defualt exapanded tab: this is string example....wow!!! Double exapanded tab: this is string example....wow!!!
Python 字符串



renmu
110***2351@qq.com
参考地址
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": # instead of the tab character, append the # number of spaces to the next tab stop char = " " * (n - pos % n) if char == "\n": pos = 0 else: pos += len(char) result += char return result使用例子
疑问例子
str = "this is\tstring" for i in range(10): print(str.expandtabs(i).replace(' ', "*"), i)空格数为一个制表符大小减去已有的字符
renmu
110***2351@qq.com
参考地址