Python 在字符串中加入变量的实例讲解

yipeiwu_com6年前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 

以上这篇Python 在字符串中加入变量的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python读写csv文件并增加行列的实例代码

python读写csv文件并增加行列,具体代码如下所示: # -*- coding: utf-8 -*- """ Created on Thu Aug 17 11:28:17 201...

Python关于excel和shp的使用在matplotlib

Python关于excel和shp的使用在matplotlib

关于excel和shp的使用在matplotlib 使用pandas 对excel进行简单操作 使用cartopy 读取shpfile 展示到matplotlib中 利用s...

详解Python迭代和迭代器

我们将要来学习python的重要概念迭代和迭代器,通过简单实用的例子如列表迭代器和xrange。 可迭代 一个对象,物理或者虚拟存储的序列。list,tuple,strins,dictt...

Python编程中的文件读写及相关的文件对象方法讲解

python文件读写 python 进行文件读写的内建函数是open或file file_hander(文件句柄或者叫做对象)= open(filename,mode) mode: 模式...

Python日期时间对象转换为字符串的实例

1、标准转换格式符号说明 %a 本地星期的短名称 如:Sun, Mon, ..., Sat (en_US); So, Mo, ..., Sa (de_DE) %A 本地星期全名称 如...