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()函数
对于变量较多的情况,加入加'+'或者'%'相对比较麻烦,这种情况下可以使用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
相关推荐
文山羊 2020-10-20
楼上小宇home 2020-09-26
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
世事一场大梦 2020-11-17
xiaoseyihe 2020-11-16
Morelia 2020-11-03
CloudXli 2020-11-03
文山羊 2020-10-31
comtop0 2020-10-31
pythonxuexi 2020-10-30
三石 2020-10-29