极客进化岛
技术自由路

python中的格式化输出

age = input("Age:")
job = input("Job:")
hobby = input("Hobbie:")
info = '''
---------------info of %s ------------
Name  :  %s 
Age   :   %s
job   :   %s
Hobbie :  %s
----------------end--------

''' %(name,name,age,job,hobby)
print(info)

%s 是字符串占位符, %d是数字占位符,若把上面的age换成%d,就只能输入数字,否则会报错。

执行结果:

C:\Users\Administrator\Desktop>python test.py
Name:xx
Age:55
Job:tea
Hobbie:dd

---------------info of xx ------------
Name  :  xx
Age   :   55
job   :   tea
Hobbie :  dd
----------------end--------

如果在字符串中出现了%s这样的占位符,那么所有的%都将变成占位符,如果像下面这样输入一定会报错:

print("我叫%s, 今天37岁,我正在教python,你已经学习了2%了" % '高胜寒')

输出结果:

C:\Users\Administrator\Desktop>python test.py
Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print("我叫%s, 今天37岁,我正在教python,你已经学习了2%了" % '高胜寒')
TypeError: not enough arguments for format string

所以遇到这样的问题,我们需要用%%来表示字符串中的%

print("我叫%s, 今天37岁,我正在教python,你已经学习了2%%了" % '高胜寒')

输出结果:

C:\Users\Administrator\Desktop>python test.py
我叫高胜寒, 今天37岁,我正在教python,你已经学习了2%了
赞(0)
未经允许不得转载:极客进化岛 » python中的格式化输出