f-string格式化字符串常量

1、F字符串(F-Strings)

name = "eric"
age = 10
res = f"hi my name is {name} i'm {age} now"
print(res)
"""
hi my name is eric i'm 10 now
res = f"A total number is {2*3}"
print(res)
"""
A total number is 6
"""

2、dir()返回任何对象的属性和方法。

lst = [1,2,3]
print(dir(lst))
"""
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__','__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
"""

3、装饰器。

def logging(func):
    def log_function_called():
        print(f"{func} called")
    return log_function_called

@logging
def my_name():
    print("chris")

my_name()
"""
<function my_name at 0x0000000002BA9AF0> called
"""
def logging(func):
    def log_function_called():
        print(f"{func} called")
        func()
    return log_function_called

@logging
def my_name():
    print("chris")

my_name()
"""
<function my_name at 0x0000000002989AF0> called
chris
"""
import time
def count_time(func):
    def wrapper( ):
        start = time.time()
        func( )
        end = time.time()
        print (end-start)
    return wrapper


number=0
@count_time
def f( ):
    global number
    for i in range(10):
        number+=i
    print(number)

f()
"""
45
0.02000117301940918
"""

 4、F-Strings可以调用函数。

fruit="orange"
num=10
print(f"I like {fruit.upper()}I ate {num} oranges")
"""
I like ORANGEI ate 10 oranges
"""

5、F-Strings可以使用lambda表达式。

print(f"{(lambda x: x**2)(5)}")
"""
25
"""
原文地址:https://www.cnblogs.com/yijierui/p/13907149.html