Adding variables to python characters

Sometimes, we need to add corresponding variables to the string. The following provides several methods for adding variables to the string:

1. + hyphen

[python]  view plain copy  
 
  1. name =  'zhangsan'  
  2. print('my name is '+name)  
  3.   
  4. #The result is my name is zhangsan  

2. % character

[python]  view plain copy  
 
  1. name =  'zhangsan'  
  2. age = 25  
  3. price = 4500.225  
  4. print('my name is %s'%(name))  
  5. print('i am %d'%(age)+' years old')  
  6. print('my price is %f'%(price))  
  7. #Keep the specified number of decimal places (rounded up)  
  8. print('my price is %.2f'%(price))  
  9.   
  10. The result is  
  11. my name is zhangsan  
  12. i am 25 years old  
  13. my price is 4500.225000  
  14. my price is 4500.23  

3. format() function

For the case of many variables, it is relatively troublesome to add '+' or '%'. In this case, the format function can be used
[python]  view plain copy  
 
  1. name =  'zhangsan'  
  2. age = 25  
  3. price = 4500.225  
  4. info = 'my name is {my_name},i am {my_age} years old,my price is {my_price}'\  
  5.     .format(my_name=name,my_age=age,my_price=price)  
  6. print(info)  
  7.   
  8. The result is:  
  9. my name is zhangsan,i am 25 years old,my price is 4500.225  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325020363&siteId=291194637