Length of tab character

怎甘沉沦 提交于 2021-01-03 16:57:59

问题


Is it possible to type a specific width of tab using \t, or is it a system defined length?

Example code:

print 'test\ttest 2'

回答1:


It is not possible. But, you can replace every tab with custom amounts of spaces using str.expandtabs:

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

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

Edit: note that when using str.expandtabs, the width of tab will depend on where in string the tab is:

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

If you want each tab to be replaced by specifyed number of spaces, you can use 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'


来源:https://stackoverflow.com/questions/33421405/length-of-tab-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!