您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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
python 2022/1/1 18:35:50 有472人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶