Python 字符串占位符與.format格式化的用法


直接上代碼,一看就能懂:

my_name = 'Richard'
age = 22
salary = int(input('please input your salary:'))

#method 1 占位符,%s表示只能接受string, %d代表只能接受數字,所以上邊salary接受的input輸入,需要強轉為int類型
res1 = 'res1: My name is %s ,I\'m %d years old, my salary is %d'%(my_name,age,salary)
print(res1)

#method 2 .format的用法1,需要用{n}作占位符,占位符從0開始
res2 = 'res2: My name is {0} ,I\'m {1} years old, my salary is {2}'.format(my_name,age,salary)
print(res2)

#method 3 .format的用法2,需要用{alias}作占位符
res3 = 'res3: My name is {_name} ,I\'m {_age} years old, my salary is {_salary}'.format(_name=my_name,_age=age,_salary=salary)
print(res3)

運行結果:

please input your salary:22222
res1: My name is Richard ,I'm 22 years old, my salary is 22222
res2: My name is Richard ,I'm 22 years old, my salary is 22222
res3: My name is Richard ,I'm 22 years old, my salary is 22222

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM