打印中的标签不是一致的python

ewa*_*wan 9 python string

我希望在打印中有真正的标签但\t只放置空格.例如:

 first:ThisIsLong         second:Short
 first:Short         second:ThisIsLong
 first:ThisIsEvenLonger         second:Short
Run Code Online (Sandbox Code Playgroud)

我将如何解决它,以便我可以拥有所有的第一,所有的秒数排队.例如:

 first:ThisIsLong         second:Short
 first:Short              second:ThisIsLong
 first:ThisIsEvenLonger   second:Short
Run Code Online (Sandbox Code Playgroud)

mjw*_*ich 10

您可以使用格式来对齐字符串.例如,您可以告诉python第一列应该是20个字符长,第二列应该是10,左对齐.

例如:

string_one = 'first:ThisIsLong'
string_two = 'second:Short'

print( '{:<20s} {:<10s}'.format(string_one, string_two) )
Run Code Online (Sandbox Code Playgroud)

将打印:

first:ThisIsLong     second:Short
Run Code Online (Sandbox Code Playgroud)

这里的第一个格式化描述符({:<20s})说:

'<'左对齐,20至少20个字符,s因为它是一个字符串


fal*_*tru 5

而不是使用tab(\t),我建议使用printf样式格式的字符串格式str.format:

rows = [
    ['first:ThisIsLong', 'second:Short'],
    ['first:Short', 'second:ThisIsLong'],
    ['first:ThisIsEvenLonger', 'second:Short'],
]
for first, second in rows:
    print('%-25s %s' % (first, second))
Run Code Online (Sandbox Code Playgroud)

要么

print('{:<25} {}'.format(first, second))
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 5

计算每列所需的最大宽度,然后使用字符串格式来组成指定所需宽度的格式:

data = [['first:ThisIsLong', 'second:Short'],
        ['first:Short', 'second:ThisIsLong'],
        ['first:ThisIsEvenLonger', 'second:Short']]

widths = [max([len(item) for item in col]) for col in zip(*data)]
fmt = ''.join(['{{:{}}}'.format(width+4) for width in widths])
for row in data:
    print(fmt.format(*row))
Run Code Online (Sandbox Code Playgroud)

产量

first:ThisIsLong          second:Short         
first:Short               second:ThisIsLong    
first:ThisIsEvenLonger    second:Short         
Run Code Online (Sandbox Code Playgroud)


Joh*_*man 5

Pythonprint函数将字符串发送到标准输出。标准输出如何处理这些字符串取决于输出设备。的默认解释\t是前进到下一个制表位,按照惯例,它是字符位置,它是\t出现位置之后的下一个 8 的倍数(从左侧开始计算字符位置)。

例如,如果我运行:

babynames = [('kangaroo', 'joey'), ('fox', 'kit'), ('goose','gosling')]
for x,y in babynames: print(x + '\t' + y)
Run Code Online (Sandbox Code Playgroud)

我得到:

kangaroo        joey
fox     kit
goose   gosling
Run Code Online (Sandbox Code Playgroud)

我在空闲时得到了上述内容。kangaroo占据第 0-7 列。\t位于第 8 列,因此制表符位于第 16 列之后的下一个 8 倍数(下一个制表位)——这确实是您看到的位置joey。在接下来的两行中——第一个单词之后的下一个制表位在第 8 列。这表明(至少在 IDLE shell 中)Python正在使用真正的制表符。

从这个意义上说,标签有点烦人。它们只能用于对齐具有一定烦人难度的可变长度字符串数据。正如其他人所指出的,解决方案是不使用制表符,而是使用format