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

2024-12-09 08:31:00
admin
原创
168
摘要:问题描述:我有一些如下代码:score = 100 name = 'Alice' print('Total score for %s is %s', name, score) 我希望它打印出来Total score for Alice is 100,但我得到的却是Total score for %s is %...

问题描述:

我有一些如下代码:

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。如何才能让所有内容以正确的顺序和正确的格式打印出来?


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


解决方案 1:

有很多方法可以做到这一点。要使用%-formatting 修复当前代码,您需要传入一个元组:

  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))
  1. 使用带有数字的新式字符串格式(对于重新排序或多次打印相同的数字很有用):

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

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

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
  1. 使用 Python 3.6 中的新f字符串格式:

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

解决方案 2:

有很多种方法可以打印。

我们来看另一个例子。

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

解决方案 3:

使用:.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))

或者: 从Python 3.6f-string格式化:

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

解决方案 4:

在 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}.')

会做。

它更加高效,更加优雅。

解决方案 5:

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

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

它适用于 Python 2.7 和 3.X。

注意:如果分数是int,则应将其转换为str

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

解决方案 6:

只需按照

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

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

解决方案 7:

尝试一下:

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

解决方案 8:

使用f-string

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

或者

使用.format

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

解决方案 9:

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

%s可以替换为%d%f

解决方案 10:

如果score是数字,那么

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

如果分数是字符串,则

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

如果分数是数字,那么它就是%d,如果分数是字符串,那么它就是%s,如果分数是浮点数,那么它就是%f

解决方案 11:

最简单的方法如下

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

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

解决方案 12:

这是我的做法:

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

for请记住在 之后和 之前和之后留一个空格is

解决方案 13:

这可能是casting issueCasting syntax当您尝试组合两个不同的 时,就会发生这种情况types of variables。由于我们无法将 a 转换stringintegerfloat,因此我们必须将我们的 转换integersstring。您可以这样做: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>

运行代码片段Hide results展开片段

解决方案 14:

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

请注意,这会打印name='Alice',而不仅仅是'Alice'

所有功能:

  • 您可以打印变量名称变量值。这对于调试打印非常有用。如果您不需要某个变量,请省略=符号。

  • 如果你重命名、删除或添加任何调试变量,此打印行将保持正确

  • 不用担心对齐问题。如果你有多个变量,那么第 4 个参数是score还是age?好吧,你不必担心,无论如何它都是正确的。

  • 请注意,这仅适用于 Python 3.8+

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用