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

我用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"
1637937 次浏览

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

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

, in print函数用一个空格分隔项目:

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

你可以使用字符串格式化来做到这一点:

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"

你可以使用格式化字符串:

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

或者在这个简单的例子中:

print "There are ", births, "births"

两个

第一个

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

我将您的脚本复制并粘贴到一个.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

我希望这能有所帮助。

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

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

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

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

你首先要创建一个变量:例如:D = 1。然后这样做,但替换字符串与任何你想要:

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

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

使用字符串格式化

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

从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

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

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

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

使用f-string

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))
如果你使用的是python 3.6或最新版本, F-string是最好的和简单的

print(f"{your_varaible_name}")

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

在中间用,(逗号)就可以了。

为了更好地理解,请参阅下面的代码:

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

如果你在字符串和变量之间使用逗号,就像这样:

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

从Python-3.8开始,你可以使用带有变量的名字 printing!

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?好吧,你不在乎,不管它是正确的。