编程语言
首页 > 编程语言> > Python 字符串中引入变量

Python 字符串中引入变量

作者:互联网

在字符串中加入变量有三种方法:

 

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 zhangsan  
i am 25 years old  
my price is 4500.225000  
my price is 4500.23  

 

3、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 is 4500.225

//可固定位置
{0}{0}.format(name)

 

"activityNameMultiLang": "{{\"English\":\"english 活动主题 {randomNum}\",\"Chinese\":\"chinese 活动主题 {randomNum}\"}}".format(randomNum=randomNum),

标签:变量,format,Python,zhangsan,price,print,字符串,my,name
来源: https://www.cnblogs.com/QingshanY/p/16110525.html