制表符长度

Col*_*lup 3 python python-2.7

是否可以使用特定宽度的tab键入\t,还是系统定义的长度?

示例代码:

print 'test\ttest 2'
Run Code Online (Sandbox Code Playgroud)

Gin*_*lus 11

这不可能.但是,您可以使用以下内容替换每个选项卡的自定义空格量str.expandtabs:

print repr('test\ttest 2'.expandtabs())
# output: 'test    test 2'

print repr('test\ttest 2'.expandtabs(2))
# output: 'test  test 
Run Code Online (Sandbox Code Playgroud)

编辑:请注意,使用时str.expandtabs,选项卡的宽度将取决于选项卡在字符串中的位置:

print repr('test\ttest 2'.expandtabs(8))
print repr('tessst\ttest 2'.expandtabs(8))
# output: 'test    test 2'
#         'tessst  test 2'
Run Code Online (Sandbox Code Playgroud)

如果希望每个选项卡都被指定的空格数替换,则可以使用str.replace:

print repr('test\ttest 2'.replace('\t', ' ' * 8))
print repr('tessst\ttest 2'.replace('\t', ' ' * 8))
# output: 'test        test 2' 
#         'tessst        test 2'
Run Code Online (Sandbox Code Playgroud)