格式化字符串的方式
- %格式化
- 模板字符串
- 字符串的format方法
- 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岁