如何在 Python 中在同一行打印变量和字符串?[重复]

2025-02-17 09:24:00
admin
原创
64
摘要:问题描述:我正在使用 Python 计算如果每 7 秒有一个孩子出生,那么 5 年内会有多少个孩子出生。问题出在最后一行。当我在变量的两侧打印文本时,如何让变量工作?这是我的代码:currentPop = 312032486 oneYear = 365 hours = 24 minutes = 60 seco...

问题描述:

我正在使用 Python 计算如果每 7 秒有一个孩子出生,那么 5 年内会有多少个孩子出生。问题出在最后一行。当我在变量的两侧打印文本时,如何让变量工作?

这是我的代码:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " births "births"

解决方案 1:

打印时使用,分隔字符串和变量:

print("If there was a birth every 7 seconds, there would be: ", births, "births")

,在打印函数中,各个项目之间用一个空格分隔:

>>> print("foo", "bar", "spam")
foo bar spam

或者更好地使用字符串格式:

print("If there was a birth every 7 seconds, there would be: {} births".format(births))

字符串格式化功能更加强大,还允许您执行一些其他操作,例如填充、对齐、宽度、设置精度等。

>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002             1.100000
  ^^^
  0's padded to 2

演示:

>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be:  4 births

# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births

解决方案 2:

Python 是一种非常通用的语言。您可以使用不同的方法打印变量。我在下面列出了五种方法。您可以根据自己的方便使用它们。

例子:

a = 1
b = 'ball'

方法 1:

print('I have %d %s' % (a, b))

方法 2:

print('I have', a, b)

方法 3:

print('I have {} {}'.format(a, b))

方法 4:

print('I have ' + str(a) + ' ' + b)

方法 5:

print(f'I have {a} {b}')

输出结果为:

I have 1 ball

解决方案 3:

还有两个

第一个

>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.

添加字符串时,它们会连接起来。

第二个

此外format(Python 2.6 及更新版本)字符串方法可能是标准方法:

>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.

format方法也可以用于列表

>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))  
there are five births and three deaths

或词典

>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths

编辑:

现在是 2022 年,python3 有 f 字符串。

>>> x = 15
>>> f"there are {x} births"
'there are 15 births'

解决方案 4:

如果你想使用python 3,这非常简单:

print("If there was a birth every 7 second, there would be %d births." % (births))

解决方案 5:

您可以使用f-string.format()方法

使用 f 字符串

print(f'If there was a birth every 7 seconds, there would be: {births} births')

使用 .format()

print("If there was a birth every 7 seconds, there would be: {births} births".format(births=births))

解决方案 6:

从 python 3.6 开始,您可以使用文字字符串插值。

births = 5.25487
>>> print(f'If there was a birth every 7 seconds, there would be: {births:.2f} births')
If there was a birth every 7 seconds, there would be: 5.25 births

解决方案 7:

您可以使用格式字符串:

print "There are %d births" % (births,)

或者在这个简单的情况下:

print "There are ", births, "births"

解决方案 8:

如果你使用的是 python 3.6 或最新版本,那么 f-string 是最好且最简单的

print(f"{your_varaible_name}")

解决方案 9:

从 Python-3.8 开始,您可以使用带有变量名称打印的 f 字符串!

age = 19
vitality = 17
charisma = 16
name = "Alice"
print(f"{name=}, {age=}, {vitality=}, {charisma=}")
# name='Alice', age=19, vitality=17, charisma=16
  • 这里几乎不可能出现命名错误!如果您添加、重命名或删除变量,您的调试打印将保持正确。

  • 调试行非常简洁

  • 不用担心对齐问题。第 4 个参数是charisma还是vitality?好吧,你不必关心,无论如何它都是正确的。

解决方案 10:

您首先要创建一个变量:例如:D = 1。然后执行此操作,但将字符串替换为您想要的任何内容:

D = 1
print("Here is a number!:",D)

解决方案 11:

在当前的 Python 版本中你必须使用括号,如下所示:

print ("If there was a birth every 7 seconds", X)

解决方案 12:

您可以使用字符串格式化来执行此操作:

print "If there was a birth every 7 seconds, there would be: %d births" % births

或者您可以给出print多个参数,它会自动用空格分隔它们:

print "If there was a birth every 7 seconds, there would be:", births, "births"

解决方案 13:

使用字符串格式

print("If there was a birth every 7 seconds, there would be: {} births".format(births))
 # Will replace "{}" with births

如果你正在做一个玩具项目使用:

print('If there was a birth every 7 seconds, there would be:' births'births) 

或者

print('If there was a birth every 7 seconds, there would be: %d births' %(births))
# Will replace %d with births

解决方案 14:

只需在中间使用 ,(逗号)即可。

请参阅此代码以便更好地理解:

# Weight converter pounds to kg

weight_lbs = input("Enter your weight in pounds: ")

weight_kg = 0.45 * int(weight_lbs)

print("You are ", weight_kg, " kg")

解决方案 15:

我将您的脚本复制并粘贴到 .py 文件中。我使用 Python 2.7.10 按原样运行它,并收到相同的语法错误。我也在 Python 3.5 中尝试了该脚本,并收到以下输出:

File "print_strings_on_same_line.py", line 16
print fiveYears
              ^
SyntaxError: Missing parentheses in call to 'print'

然后,我修改了打印出生人数的最后一行,如下所示:

currentPop = 312032486
oneYear = 365
hours = 24
minutes = 60
seconds = 60

# seconds in a single day
secondsInDay = hours * minutes * seconds

# seconds in a year
secondsInYear = secondsInDay * oneYear

fiveYears = secondsInYear * 5

#Seconds in 5 years
print fiveYears

# fiveYears in seconds, divided by 7 seconds
births = fiveYears // 7

print "If there was a birth every 7 seconds, there would be: " + str(births) + " births"

输出为(Python 2.7.10):

157680000
If there was a birth every 7 seconds, there would be: 22525714 births

我希望这会有所帮助。

解决方案 16:

稍有不同:使用 Python 3 并在同一行打印几个变量:

print("~~Create new DB:",argv[5],"; with user:",argv[3],"; and Password:",argv[4]," ~~")

解决方案 17:

Python 3 简介

最好使用格式选项

user_name=input("Enter your name : )

points = 10

print ("Hello, {} your point is {} : ".format(user_name,points)

或者将输入声明为字符串并使用

user_name=str(input("Enter your name : ))

points = 10

print("Hello, "+user_name+" your point is " +str(points))

解决方案 18:

如果在字符串和变量之间使用逗号,如下所示:

print "If there was a birth every 7 seconds, there would be: ", births, "births"
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2545  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1551  
  建筑工程全生命周期涉及从项目规划、设计、施工到运营维护等多个复杂阶段,每个阶段都产生和依赖大量信息。PLM(产品生命周期管理)系统作为一种整合数据、流程和人员的数字化解决方案,正逐渐成为建筑行业实现高效协同与可持续发展的关键支撑。通过数字化转型,PLM系统能够优化各阶段的工作流程,提升项目整体质量和效率,为建筑工程的全...
plm是什么软件   1  
  产品生命周期管理(PLM)系统在企业资源成本率优化方面发挥着至关重要的作用。通过构建有效的数据模型,PLM系统能够整合企业各个环节的数据,为资源成本的精准分析和优化提供有力支持。这不仅有助于企业降低成本,还能提升产品质量和市场竞争力。PLM系统概述PLM系统是一种用于管理产品从概念设计到退役全生命周期过程中所有信息和流...
PLM项目管理软件   1  
  产品生命周期管理(PLM)系统在现代企业的产品研发、生产与管理过程中扮演着至关重要的角色。它整合了从产品概念设计到产品退役的全生命周期数据与流程,助力企业提升效率、降低成本并增强创新能力。随着技术的不断发展,到 2025 年,PLM 系统将具备一系列核心功能模块,这些模块将深度影响企业的运营与发展。产品数据管理模块产品...
plm是什么意思   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

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

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

内置subversion和git源码管理

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

免费试用