教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 python 如何引用变量

python 如何引用变量

发布时间:2021-04-11   编辑:jiaochengji.com
教程集为您提供python 如何引用变量等资源,欢迎您收藏本站,我们将为您提供最新的python 如何引用变量资源

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

1、 连字符

name = 'zhangsan'
print('my name is ' name)

结果为

my name is zhangsan

相关推荐:《Python入门教程

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

您可能感兴趣的文章:
Python你知道多少?教你玩转Python变量与常量!
python如何定义一个全局变量
Python基本语法与变量的相关介绍
Python __del__方法:销毁对象
python 如何定义全局变量
python类怎么定义全局变量
python中r代表什么意思
python如何对变量赋值
python如何调用模块
python如何打印变量

[关闭]
~ ~