【问题标题】:'print' command in Python (print in the same line)Python中的“打印”命令(在同一行打印)
【发布时间】:2017-06-05 10:51:35
【问题描述】:

我正在使用 jupyter 笔记本。我想以一般形式打印一个简单的整数矩阵,即我希望输出如下所示: a[0][0] = 1 a[0][1] = 2 a[1][0] = 3 a[1][1] = 4

这是我的程序:

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print ("a[",i,"][",j,"] =",a[i][j],"\t",),
    print ("\n")

但我得到的输出是:

Enter the number of columns: 2
Enter the number of rows: 2
 Enter the elements: 1
 Enter the elements: 2
 Enter the elements: 3
 Enter the elements: 4
a[ 0 ][ 0 ] = 1     
a[ 0 ][ 1 ] = 2     


a[ 1 ][ 0 ] = 3     
a[ 1 ][ 1 ] = 4 

循环中的 print(), 函数会换行,即使我在它后面加了一个逗号。请帮我获得所需的输出格式。谢谢。

【问题讨论】:

  • 这是python 2还是python 3?
  • @Rawing 因为括号没有出现在输出中,我们必须断定它是python 3(或print_function在python 2中使用)。
  • print() 函数(来自 Python 3)的使用方式与 Python 2 中的print 语句不同。在函数使用end=""参数来抑制换行符结束。
  • 非常感谢,现在可以使用了 :)

标签: python jupyter


【解决方案1】:

这不会打印新行

print(something,end="")

和你的代码

column = int(input("Enter the number of columns: "))
row = int (input("Enter the number of rows: "))
a=[[0 for x in range(column)] for y in range(row)]
for i in range (0, row):
    for j in range (0, column):
        a[i][j]=int(input(" Enter the elements: "))
for i in range (0, row):
    for j in range (0, column):
        print("a[%d][%d] = %d "%(i,j,a[i][j]),end="")

【讨论】:

    【解决方案2】:

    其他答案很好,但更可读的代码是这样的:

    some_string = ''
    for i in range (0, row):
        for j in range (0, column):
            some_string += "a[{}][{}]= {} ".format(i,j,a[i][j])
    print(some_string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多