Study 2 —— 格式化输出
打印人物信息的两种方法
第一种:
Name = input('Input your name: ') Age = input('Input your age: ') Job = input('Input your job: ') Hometown = input('Input your hometown: ') print('---------- Info of', Name,'----------') print('Name: ', Name) print('Age: ', Age) print('Job: ', Job) print('Hometown: ', Hometown) print('------------- End -------------')
第二种:
Name = input('Input your name: ') Age = input('Input your age: ') Job = input('Input your job: ') Hometown = input('Input your hometown: ') info = ''' ---------- Info of %s ---------- Name: %s Age : %s Job : %s Hometown: %s -------------- End ------------- ''' % (Name, Name, Age, Job, Hometown)
print(info)
两种方法实现的结果都如下所示:
C:\Users\Administrator\Desktop>python info.py
Input your name: Lisa
Input your age: 18
Input your job: modal
Input your hometown: UK
---------- Info of Lisa ----------
Name: Lisa
Age : 18
Job : modal
Hometown: UK
-------------- End -------------
注:第二种方法是将人物信息进行格式化输入输出,更加方便. %s是占位符
%s 字符串(string)
%d 数字(digit)
%f 小数(float)
所以上面的代码还可以这样写:
Name = input('Input your name: ')
Age = int(input('Input your age: '))
Job = input('Input your job: ')
Hometown = input('Input your hometown: ')
info = '''
---------- Info of %s ----------
Name: %s
Age : %d
Job : %s
Hometown: %s
-------------- End -------------
''' % (Name, Name, Age, Job, Hometown)
print(info)