formatted output
format output
Ask the user to enter a username and age, then print the following format:
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))
Notice:
print('My name is %s,my age is %d' %(name,age))
age is a string type and cannot be passed to %d, so an error will be reported
print('my name is %s my age is %d ' %(name,int(age))) #Force character type conversion str-->int
Exercise: User enters name, age, job, hobbies, and prints it in the following format
------------ info of Egon -----------
Name : Egon
Age : 22
Sex : male
Job : Teacher
------------- end -----------------
code
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)
)