如何在linux终端中以单行打印输出

时间:2018-03-08 14:29:17

标签: python python-2.7

以下是代码:

data2 = [["jsdfgweykdfgwey",
          "kdgwehogfdoyeo",
          "ndlgyehwfgdiye",
          "ndfluiwgmdfho"],
          ["---------------------------------------------------------------------------------",
           "-------------------------------------------------------------------------------",
           "------------------------------------------------------------------------------",
           "-----------------------------------------------------------------------------"],
          ["kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt1",
           "kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt2",
           "kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt3",
           "kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt4\
kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt4 \
kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt4"]]

data = [x for x in data2 if x is not None]
col_width = max(len(word) for row in data for word in row) + 2
for row in data:
    print "".join(word.ljust(col_width) for word in row)#print in single line in output console.

无法正确打印输出

如何在命令输出(OS Linux)中以单行打印输出

或以列方式打印以进行长行打印的任何其他建议。

1 个答案:

答案 0 :(得分:0)

列表中的每个元素都会按照您的意愿打印为组合字符串。但是通过执行word.ljust(col_width)步骤,其中col_width大约为140,您将占用大量空白空间进行打印。如果您的控制台尺寸很小,您似乎要在新行中打印。尝试将col_width替换为10,您可能会将data2 [0]的元素打印在一行中。

如果您希望将data2打印为单个字符串,则可以执行以下操作:

tmp=''
for row in data:
    a = " ".join(word.ljust(col_width) for word in row)
    tmp = tmp + a

tmp将一个接一个地包含在字符串中的data2的每个元素