(三)格式化输出

格式化输出

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

猜你喜欢

转载自www.cnblogs.com/morron/p/8858918.html