Study 2 —— 格式化輸出

打印人物信息的兩種方法
第一種:python

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

 

第二種:git

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)

  

兩種方法實現的結果都以下所示:spa

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


因此上面的代碼還能夠這樣寫:字符串

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)
相關文章
相關標籤/搜索