首页 > 解决方案 > 在 Python 中打印变量和字符串

问题描述

我正在尝试打印以下行:

“我的名字是约翰史密斯。”

“我的名字是约翰史密斯,我住在芝加哥”

我住在芝加哥”

我的代码如下:

 name = 'John Smith'
 age = 25
 location = 'CHICAGO' # change this to lower case when printing
 print('My name is %s.')
  print('My name is %s, and I live in %s' )
  print(f'My name is {name}.')
  'and I live in location.lower()

如何从顶部获得结果?

标签: pythonstringprinting

解决方案


#!/usr/bin/env python3

name = 'john smith'
age = 25
location = 'chicago'
print ('My name is %s, and I live in %s. I am %s years old.' %  (name, location, str(age)))

输出:

我的名字是约翰史密斯,我住在芝加哥。我25岁。

顺便说一句,我建议您阅读这篇文章:https ://realpython.com/python-string-formatting/


推荐阅读