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

时间:2016-01-12 02:23:00

标签: python string

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

 first:ThisIsLong         second:Short
 first:Short         second:ThisIsLong
 first:ThisIsEvenLonger         second:Short

我将如何解决这个问题,以便我可以拥有所有的第一,并且所有的秒数排成一列。例如:

 first:ThisIsLong         second:Short
 first:Short              second:ThisIsLong
 first:ThisIsEvenLonger   second:Short

5 个答案:

答案 0 :(得分:8)

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

例如:

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

print( '{:<20s} {:<10s}'.format(string_one, string_two) )

将打印:

first:ThisIsLong     second:Short

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

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

答案 1 :(得分:5)

我建议使用printf-style formattingstr.format使用字符串格式,而不是使用标签rows = [ ['first:ThisIsLong', 'second:Short'], ['first:Short', 'second:ThisIsLong'], ['first:ThisIsEvenLonger', 'second:Short'], ] for first, second in rows: print('%-25s %s' % (first, second)) ):

print('{:<25} {}'.format(first, second))

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))

答案 2 :(得分:4)

Python print函数将字符串发送到标准输出。这些字符串的标准输出取决于输出设备。 \t的默认解释是前进到下一个tab stop,按惯例,它是字符位置,它是\t出现位置后的下一个8的倍数(计算字符位置)从左边开始0)。

例如,如果我跑:

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

我明白了:

kangaroo        joey
fox     kit
goose   gosling

我在IDLE中得到了上述内容。 kangaroo占据0-7列。 \t位于第8列,因此选项卡位于第16列后,下一个8(下一个制表位) < - >确实是joey的位置。在接下来的两行中 - 第一个单词位于第8列之后的下一个制表位。这表明(至少在IDLE shell中)Python 使用真正的标签。

这种意义上的标签有点烦人。它们只能用于将可变长度的字符串数据与一定量的恼人难度对齐。正如其他人已经指出解决方案是不使用制表符而是使用format

答案 3 :(得分:3)

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

first:ThisIsLong          second:Short         
first:Short               second:ThisIsLong    
first:ThisIsEvenLonger    second:Short         

产量

setwd("C:\\Users\\Anonymous\\Desktop\\Data 2014")

file_list <- list.files()

for (file in file_list){

# if the merged dataset doesn't exist, create it
if (!exists("dataset")){
dataset <- read.table(file, header=TRUE, sep="\t")
}

# if the merged dataset does exist, append to it
if (exists("dataset")){
temp_dataset <-read.table(file, header=TRUE, sep="\t")
dataset<-rbind(dataset, temp_dataset)
rm(temp_dataset)
}

}

答案 4 :(得分:0)

最Python化的方法是:

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

print(f'{string_one:<20s} {string_two:<10s}')

您可以使用F字符串(格式字符串)来对齐字符串。例如,您可以告诉python第一列应为20个字符长,第二列应为10个字符,左对齐。

使用此F字符串将打印:

first:ThisIsLong     second:Short

细分

f'{ 在此处插入变量_ :<20s}'说:

:之前的所有内容并采用以下格式:<左对齐,20至少20个字符,s,因为它是字符串。

使用mjwunderlich的格式。