字符串格式化的方法

格式化字符串的方式

  1. %格式化
  2. 模板字符串
  3. 字符串的format方法
  4. fstring
print("%s,It's %d dollars"%("wow",4))
# 通过Template对象封装  $放置一些占位符,并通过substitute方法用实际的值替换这些占位符

from string import Template

template1 = Template('$s是我最喜欢的编程语言,$s非常容易学习,而且功能强大')
print(template1.substitute(s = 'Python'))
# Python是我最喜欢的编程语言,Python非常容易学习,而且功能强大

template2 = Template('${h}ello world')
print(template2.substitute(h = 'abc'))
# abcello world

template3 = Template('$dollar$$相当于多少$pounds英镑')
print(template3.substitute(dollar=20,pounds=16))
# 20$相当于多少16英镑

data = {}
data['dollar'] = 30
data['pounds'] = 25
print(template3.substitute(data))
# 30$相当于多少25英镑
# q1
# 默认方式(传入的参数与{}一一对应)、命名参数和位置参数{2}

# q2
s1 = 'Today is {},the temperature is {} degrees.'
print(s1.format('Saturday',24))

s2 = 'Today is {day},the temperature is {degree} degrees.'
print(s2.format(degree = 30, day='Sunday'))

s3 = 'Today is {week},{}, the {} temperature is {degree}'
print(s3.format('abcd',12345,degree=24,week='Sunday'))

s4 = 'Today is {week},{1}, the {0} temperature is {degree} degrees.'
print(s4.format('abcde',1234,degree = 45,week='Sunday'))

class Person:
    def __init__(self):
        self.age = 20
        self.name = 'Bill'

person = Person()

s5 = "My name is {p.name},my age is {p.age}."
print(s5.format(p = person))

name = 'Bill'
age = 20

def getAge():
    return 21

s = f"我是{name},我今年{age}岁,明年{getAge()}岁"

print(s) #我是Bill,我今年20岁,明年21岁

class Person:
    def __init__(self):
        self.name = 'Mike'
        self.age = 40
    def getAge(self):
        return 41

person = Person()

s1 = f"我是{person.name},我今年{person.age}岁,明年{person.getAge()}岁"
print(s1) #我是Mike,我今年40岁,明年41岁

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值