Py学习  »  Python

Python 中 F-strings 的 9 种创意用法

数据STUDIO • 8 月前 • 265 次点击  


1. 基本变量插值

可以将变量直接插入字符串。

name = "云朵君"
age = 30
print(f"My name is {name} and I am {age} years old.")
My name is 云朵君 and I am 30 years old.

2. 表达式求值

可以在 f-strings 中包含表达式。

a = 10
b = 5
print(f"Sum of {a} and {b} is {a + b}.")
Sum of 10 and 5 is 15.

3. 格式化数字

F-strings 可以轻松格式化数字以提高可读性。

value = 1234.56789
print(f"Formatted value: {value:.2f}")
Formatted value: 1234.57

4. 使用字典

可以在 f-strings 中访问字典键。

person = {'name''Bob''age'28}
print(f"Person's name is {person['name']}and age is {person['age']}.")
Person's name is Boband age is 28.

5. 调用函数

F-strings 可以在花括号内调用函数。

def greet(name):
    return f"Hello, {name}"

print(f"Greeting: {greet('Charlie')}")
Greeting: Hello, Charlie

6.使用对象属性

可以直接在 f-string 中访问对象属性。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
p = Person('Alice'25)
print(f"{p.name} is {p.age} years old.")
Alice is 25 years old.

7. 多行 F-strings

F-strings支持带有三重引号的多行字符串。

name = "John"
age = 45
info = f"""
Name: {name}
Age: {age}
"""

print(info)
Name: John
Age: 45

8.条件表达式

可以直接在 f-strings 中包含条件表达式。

score = 85
print(f"You {'passed' if score >= 50 else 'failed'} the test.")
You passed the test.

9. 填充和对齐

F-strings 可以控制文本的宽度和对齐方式,这对于格式化表格很有用。

for i in range(16):
    print(f"{i:<5} {i**2:<5} {i**3:<5}")
1     1     1    
2 4 8
3 9 27
4 16 64
5 25 125

🏴‍☠️宝藏级🏴‍☠️ 原创公众号『数据STUDIO』内容超级硬核。公众号以Python为核心语言,垂直于数据科学领域,包括可戳👉 PythonMySQL数据分析数据可视化机器学习与数据挖掘 爬虫 等,从入门到进阶!

长按👇关注- 数据STUDIO -设为星标,干货速递

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/176147
 
265 次点击