如何在同一行上同时打印多个内容(固定文本和/或变量值)?

问题描述 投票:0回答:14

我有一些代码,例如:

score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)

我希望它打印出

Total score for Alice is 100
,但我却得到了
Total score for %s is %s Alice 100
。如何才能以正确的顺序和正确的格式打印所有内容?


另请参阅:如何在同一行上一次打印多个内容? ; 如何将变量的值放入字符串中(将其插入字符串中)?

python printing python-3.x arguments
14个回答
677
投票

有很多方法可以做到这一点。要使用

%
格式修复当前代码,您需要传入一个元组:

  1. 将其作为元组传递:

    print("Total score for %s is %s" % (name, score))
    

具有单个元素的元组看起来像

('this',)

以下是其他一些常见的方法:

  1. 将其作为字典传递:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

还有新式字符串格式,可能更容易阅读:

  1. 使用新式字符串格式:

    print("Total score for {} is {}".format(name, score))
    
  2. 使用带有数字的新型字符串格式(对于重新排序或多次打印相同的字符串很有用):

    print("Total score for {0} is {1}".format(name, score))
    
  3. 使用具有显式名称的新型字符串格式:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. 连接字符串:

    print("Total score for " + str(name) + " is " + str(score))
    

我认为最清晰的两个:

  1. 只需将值作为参数传递即可:

    print("Total score for", name, "is", score)
    

    如果您不希望上例中的

    print
    自动插入空格,请更改
    sep
    参数:

    print("Total score for ", name, " is ", score, sep='')
    

    如果您使用的是 Python 2,将无法使用后两个,因为

    print
    不是 Python 2 中的函数。但是,您可以从
    __future__
    导入此行为:

    from __future__ import print_function
    
  2. 使用 Python 3.6 中新的

    f
    字符串格式:

    print(f'Total score for {name} is {score}')
    

64
投票

有很多方法可以打印它。

我们再看一个例子。

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

54
投票

使用:

.format()

print("Total score for {0} is {1}".format(name, score))

或者:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

或者:

print("Total score for" + name + " is " + score)

或者:

print("Total score for %s is %d" % (name, score))

或者:

f-string
Python 3.6格式化:

print(f'Total score for {name} is {score}')

可以使用

repr
并自动添加
''

print("Total score for" + repr(name) + " is " + repr(score))

# or for advanced: 
print(f'Total score for {name!r} is {score!r}') 

23
投票

在 Python 3.6 中,

f-string
更加简洁。

在早期版本中:

print("Total score for %s is %s. " % (name, score))

在 Python 3.6 中:

print(f'Total score for {name} is {score}.')

会的。

更加高效、优雅。


15
投票

保持简单,我个人喜欢字符串连接:

print("Total score for " + name + " is " + score)

它适用于 Python 2.7 和 3.X。

注意:如果分数是 int,那么,您应该将其转换为 str:

print("Total score for " + name + " is " + str(score))

15
投票

只要按照这个

grade = "the biggest idiot"
year = 22
print("I have been {} for {} years.".format(grade, year))

grade = "the biggest idiot"
year = 22
print("I have been %s for %s years." % (grade, year))

忘记所有其他格式,否则大脑将无法映射所有格式。


12
投票

尝试一下:

print("Total score for", name, "is", score)

7
投票

使用

f-string

print(f'Total score for {name} is {score}')

或者

使用

.format

print("Total score for {} is {}".format(name, score))

6
投票
print("Total score for %s is %s  " % (name, score))

%s
可以替换为
%d
%f


5
投票

如果

score
是一个数字,那么

print("Total score for %s is %d" % (name, score))

如果分数是字符串,则

print("Total score for %s is %s" % (name, score))

如果分数是数字,则为

%d
,如果为字符串,则为
%s
,如果分数为浮点数,则为
%f


3
投票

这就是我所做的:

print("Total score for " + name + " is " + score)

记得在

for
之后以及
is
前后各留一个空格。


3
投票

最简单的方法如下

print(f"Total score for {name} is {score}")

只需在前面加上“f”即可。


0
投票

这可能是一个

casting issue
。当您尝试组合两个不同的
Casting syntax
时,会发生
types of variables
。由于我们无法始终将
string
转换为
integer
float
,因此我们必须将
integers
转换为
string
。这就是你的做法。:
str(x)
。要转换为整数,它是:
int(x)
,浮点数是
float(x)
。我们的代码将是:

print('Total score for ' + str(name) + ' is ' + str(score))

还有!运行此

snippet
查看如何转换不同
types of variables

的表格

<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
  </tr>
 <tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>


0
投票
print(f"Total score calculation complete, {name=}, {score=}")
# this will print:
# Total score calculation complete, name='Alice', score=100

请注意,这会打印

name='Alice'
,而不仅仅是
'Alice'

所有功能:

  • 您将获得变量名称以及变量值打印。这对于调试打印非常有用。如果某个变量不需要它,请省略
    =
    符号。
  • 如果您重命名、删除或添加任何调试变量,此打印行将保持正确
  • 不用担心对齐问题。如果有多个变量,第四个参数是
    score
    还是
    age
    ?好吧,你不在乎,无论如何都是正确的。
  • 请注意,这仅适用于 Python 3.8+
© www.soinside.com 2019 - 2024. All rights reserved.