如何在 Python 中在同一行打印变量和字符串?[重复]
- 2025-02-17 09:24:00
- admin 原创
- 64
问题描述:
我正在使用 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"
扫码咨询,免费领取项目管理大礼包!