Python在字串中引用變數
阿新 • • 發佈:2019-01-06
在字串中加入變數有三種方法:
1、+ 連字元
- name = 'zhangsan'
- print('my name is '+name)
- #結果為 my name is zhangsan
2、% 字元
- 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))
- #保留指定位數小數(四捨五入)
- print('my price is %.2f'%(price))
- 結果為
- my name is
- i am 25 years old
- my price is4500.225000
- my price is4500.23
3、format()函式
對於變數較多的情況,加入加'+'或者'%'相對比較麻煩,這種情況下可以使用format函式- 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)
- 結果為:
- my name is zhangsan,i am 25 years old,my price is4500.225