我是靠谱客的博主 自由唇膏,这篇文章主要介绍(三)格式化输出,现在分享给大家,希望可以做个参考。

格式化输出

format output

要求用户输入用户名和年龄,然后打印如下格式:

My name is xxx,my age is xxx.
很明显,用逗号进行字符串拼接,只能把用户输入的名字和年龄放到末尾,无法放到指定的xxx位置,而且数字也必须经过str(数字)的转换才能与字符串进行拼接。
这就用到了占位符,如:%s、%d
name= input('pls input your name: ')
age=input('pls input your age: ')
age=int(age)
#强制转换成整型
print('my name is %s my age is %s ' %(name,age))
注意:

print('My name is %s,my age is %d' %(name,age))

age为字符串类型,无法传给%d,所以会报错
print('my name is %s my age is %d ' %(name,int(age))) #强制字符类型转换str-->int

练习:用户输入姓名、年龄、工作、爱好 ,然后打印成以下格式

------------ info of Egon -----------
Name
: Egon
Age
: 22
Sex
: male
Job
: Teacher
------------- end -----------------

代码

name= input('pls input your name: ')
age=input('pls input your age: ')
sex=input('pls input your sex :')
job=input('pls input your job :')
print('---------info of Bruce ------' 'n'
'name
:' '%s'
'n'
'age
:' '%d'
'n'
'sex
:' '%s'
'n'
'job
:' '%s' 'n'
"---------end-----------"
%(name,int(age),sex,job)
)

转载于:https://www.cnblogs.com/morron/p/8858918.html

最后

以上就是自由唇膏最近收集整理的关于(三)格式化输出的全部内容,更多相关(三)格式化输出内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部