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()函数
对于变量较多的情况,加入加’+‘或者’%'相对比较麻烦,这种情况下可以使用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

原文地址:https://blog.csdn.net/appke846/article/details/80690899?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python ,可以使用字符串格式化来在字符串添加变量字符串格式化可以让你将变量的值插入到字符串的占位符,从而构建出一个新的字符串。常见的字符串格式化的方法有以下两种: 1. 使用 % 运算符进行格式化 在字符串使用 %s 占位符表示要插入一个字符串变量,用 %d 占位符表示要插入一个整数变量,用 %f 占位符表示要插入一个浮点数变量。例如: ``` name = "Alice" age = 25 height = 1.72 message = "My name is %s. I'm %d years old and %.2f meters tall." % (name, age, height) print(message) ``` 输出结果为: ``` My name is Alice. I'm 25 years old and 1.72 meters tall. ``` 在上面的例子,我们使用 %s、%d 和 %.2f 占位符来分别表示字符串、整数和浮点数变量。然后,我们使用 % 运算符来连接字符串变量,并且以元组的形式将变量传递给 % 运算符。 2. 使用 format() 方法进行格式化 使用 format() 方法可以更加灵活地进行字符串格式化。在字符串使用 {} 占位符表示要插入一个变量,然后在 format() 方法传递变量的值即可。例如: ``` name = "Alice" age = 25 height = 1.72 message = "My name is {}. I'm {} years old and {:.2f} meters tall.".format(name, age, height) print(message) ``` 输出结果为: ``` My name is Alice. I'm 25 years old and 1.72 meters tall. ``` 在上面的例子,我们使用 {} 占位符来表示要插入变量的位置,然后在 format() 方法以参数的形式传递变量的值。可以使用 {} 的数字来指定变量的位置,也可以省略数字来按照顺序插入变量。使用 : 可以对插入的变量进行格式化,例如:{:.2f} 表示要插入一个浮点数,保留两位小数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值