Sometimes, we need to add corresponding variables to the string. The following provides several methods for adding variables to the string:
1. + hyphen
- name = 'zhangsan'
- print('my name is '+name)
- #The result is my name is zhangsan
2. % character
- name = 'zhangsan'
- age = 25
- price = 4500.225
- print('my name is %s'%(name))
- print('i am %d'%(age)+' years old')
- print('my price is %f'%(price))
- #Keep the specified number of decimal places (rounded up)
- print('my price is %.2f'%(price))
- The result is
- my name is zhangsan
- i am 25 years old
- my price is 4500.225000
- 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
- name = 'zhangsan'
- age = 25
- price = 4500.225
- info = 'my name is {my_name},i am {my_age} years old,my price is {my_price}'\
- .format(my_name=name,my_age=age,my_price=price)
- print(info)
- The result is:
- my name is zhangsan,i am 25 years old,my price is 4500.225