Million annual salary python road - day11 - f-strings format

f-strings are added to the standard library python3.6 start new wording formatted output, prior to the high ratio of% s or formatted output format simplified and more efficient, very easy to use.

2.1 Simple example

His configuration is F (f) + str form of, want to replace with the position in the string {} placeholder, the format is similar, but with replacement of the contents written back in the string, he can be directly identified.

name = '章超印'
age = 17
sex = '男'
msg = F'姓名:{name},性别:{age},年龄:{sex}'  # 大写字母也可以
msg = f'姓名:{name},性别:{age},年龄:{sex}'  
print(msg)
'''
输出结果:
姓名:章超印,性别:17,年龄:男
'''

2.2 Any expression

He can add any expression, it is very easy:

print(f'{25*4}')  # 100

name = 'jacky'
print(f"全部大写:{name.upper()}")  # 全部大写:JACKY
# 字典也可以
student = {'name': '章超印', 'age': 18}
msg = f"The student is {student['name']}, age {student['age']}"
print(msg)  # The student is 章超印, age 18

# 列表也行
lst = ['章超印', 18]
msg = f'姓名:{lst[0]},年龄:{lst[1]}.'
print(msg)  # 姓名:章超印,年龄:18.


#列表推导式也可以
s = f"{[i for i in range(9) if i > 3]}"
print(s)

2.3 an insert function

Corresponding functions can be accomplished by a function, and then returns the value returned to a position corresponding to a string

def sum_a_b(a,b):
    return a + b
a = 1
b = 2
print('求和的结果为' + f'{sum_a_b(a,b)}')

More than 2.4-line f

name = 'Jacky'
age = 18
character = 'excellent'

# speaker = f'''Hi {name}.
# You are {age} years old.
# You are a {character} guy!'''

speaker = f'Hi {name}.'\
          f'You are {age} years old.'\
          f'You are a {character} guy!'
print(speaker)

2.5 Other details

print(f"{73}")                  # 73
print(f"{{73}}")                # {73}
print(f"{{{73}}}")              # {73}
print(f"{{{{73}}}}")            # {{73}}
print(f"{{{{{73}}}}}")          # {{73}}
print(f"{{{{{{73}}}}}}")        # {{{73}}}
print(f"{{{{{{{73}}}}}}}")      # {{{73}}}
print(f"{{{{{{{{73}}}}}}}}")    # {{{{73}}}}
print(f"{{{{{{{{{73}}}}}}}}}")  # {{{{73}}}}

# ! , : { } ;这些标点不能出现在{} 这里面。
# print(f'{;12}')  # 报错
# 所以使用lambda 表达式会出现一些问题。
# 解决方式:可将lambda嵌套在圆括号里面解决此问题。
x = 5
print(f'{(lambda x: x ** 2) (x)}')  # 25

Guess you like

Origin www.cnblogs.com/zhangchaoyin/p/11221138.html