在Python中哪种格式化方式可以直接使用变量
1.使用fstring方法可以直接格式化
fstring格式化字符串
- 使用参数为变量,然后在双引号""的左边添加f
name = 'Bill'
age = 20
s = f"我是{name},今年{age}岁"
print(s)
![](https://img.haomeiwen.com/i20044978/9b1b156da06b8023.png)
- 使用参数不仅仅可以是变量,也可以使用函数,然后在双引号""的左边添加f
name = 'Bill'
age = 20
def getAge(x):
return x
s = f"我是{name},今年{getAge(15)}岁"
print(s)
![](https://img.haomeiwen.com/i20044978/3affec42c8067bf4.png)
- 使用参数可以是类,然后在双引号""的左边添加f
class Person:
def __init__(self):
self.name = 'Joke'
self.age = 15
def getAge(self,newage):
return newage
person = Person()
s1 = f"我是{person.name},今年我{person.age}岁,明年我就是{person.getAge(16)}"
print(s1)
![](https://img.haomeiwen.com/i20044978/61b539f8e982a55c.png)
总结
1.fstring方式指的是在字符串中直接使用Python变量,这需要在字符串的前面用f标注
网友评论