python中格式化字符串的作用_Python中格式化的字符串文字(f字符串)?

Python现在提供了一种格式化字符串的新方法,称为f字符串。可从PEP-498下的Python 3.6获得此功能。它们之所以称为(f-string),是因为带有字符串的字母'f'前缀。字母“ f”还表示这些f字符串可用于格式化。

下面是一些示例,用于演示f字符串的用法。

程式#1name = 'Rajesh'

age = 13 * 3

fString = f'My name is {name} and my age is {age}'

print(fString)

#We can use Uppercase 'F' instead of lowercase 'f'.

print(F'My name is {name} and my age is {age}')

#As the fString valuation is done, giving another value to the variable will not change fstring value.

name = 'Zack'

age = 44

print(fString)

输出结果My name is Rajesh and my age is 39

My name is Rajesh and my age is 39

My name is Rajesh and my age is 39

Example#2 –带表达式和转换的f字符串

从datetime导入datetimename = 'Rajesh'

age = 13 * 3

dt = datetime.now()

print(f' Age after ten years will be {age + 10}')

print(f'Name with quotes = {name!r}')

print(f'Default formatted Date = {dt}')

print(f'Modified Date format = {dt: %d/%m/%Y}')

输出结果Age after ten years will be 49

Name with quotes = 'Rajesh'

Default formatted Date = 2019-02-11 14:52:05.307841

Modified Date format = 11/02/2019

Example#3:对象和属性class Vehicle:

Model = 0

Brand = ''

def __init__(self, Model, Brand):

self.Model = Model

self.Brand = Brand

def __str__(self):

return f'E[Model={self.Model}, Brand = {self.Brand}]'

Car = Vehicle (2018, 'Maruti')

print(Car)

print(f'Vehicle: {Car}\nModel is {Car.Model} and Brand is {Car.Brand}')

输出结果E[Model=2018, Brand = Maruti]

Vehicle: E[Model=2018, Brand = Maruti]

Model is 2018 and Brand is Maruti

Example#4:调用函数

我们也可以用f字符串格式调用函数。def Multiply(x,y):

return x*y

print( f'Multiply(40,20) = {Multiply(40,20)}')

输出结果Multiply(40,20) = 800

Example#5:Lambda表达式x = -40.9

print(f' Lambda absolute of (-40.9) is : {(lambda x: abs(x)) (x)}')

print(f' Lambda Square of 2^4 is: {(lambda x: pow(x, 2)) (4)}')

输出结果Lambda absolute of (-40.9) is : 40.9

Lambda Square of 24 is: 16

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值