鱼C论坛

 找回密码
 立即注册
查看: 2782|回复: 1

有关expandtabs方法的用法问题

[复制链接]
发表于 2017-2-2 17:19:51 | 显示全部楼层 |阅读模式
2鱼币
在0基础的第十四课中提到了expandtabs的用法,因为没提到参数的修改,我自己编了一个程序看了下
  1. a = 'a\tb'
  2. b = 'abc\tde'
  3. for i in range(15):
  4.     print(a.expandtabs(tabsize=i))
  5. for f in range(15):
  6.     print(b.expandtabs(tabsize=f))
复制代码


然而输出结果是
ab
a b
a b
a  b
a   b
a    b
a     b
a      b
a       b
a        b
a         b
a          b
a           b
a            b
a             b
abcde
abc de
abc de
abc   de
abc de
abc  de
abc   de
abc    de
abc     de
abc      de
abc       de
abc        de
abc         de
abc          de
abc           de
一个是空格数量对不上
第二b.expandtabs(tabsize=4)比b.expandtabs(tabsize=5)中间的空格更多?
我想问问这个参数究竟是什么原理?

最佳答案

查看完整内容

看了Python的帮助文档:Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. 输出的空格数与\t前面的字符数有关: >>> a = 'a\tb' >>> for i in range(15): ... print(a.expandtabs(tabsize=i)) ... tabsize(i) 空格数 ab 0 0 a b 1 1 a b 2 1 a b 3 2 a b 4 3 a b 5 4 a ...
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-2-2 17:19:52 | 显示全部楼层
看了Python的帮助文档:Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size.

输出的空格数与\t前面的字符数有关:
>>> a = 'a\tb'
>>> for i in range(15):
...     print(a.expandtabs(tabsize=i))
...
                           tabsize(i)   空格数
ab                                0        0
a b                                1        1
a b                                2        1
a  b                                3        2                               
a   b                                4        3
a    b                        5        4
a     b                        6        5

还有下面这个,第一个\t输出的是2个空格,第二个输出的是1个空格,第三个输出的是4个空格:
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-25 05:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表