Python中除隐式拼接与逐行加f外,多行f-string的更优写法
问题:优化Python类中字符串输出的整洁写法
我编写了如下可正常运行的代码:
class User: def __init__(self, first_name, last_name, gender, location): self.first_name = first_name self.last_name = last_name self.gender = gender self.location = location def describe_user(self): print(f"User {self.first_name} {self.last_name} is a " f"{self.gender} from {self.location}") def greet_user(self): print(f"Hello there {self.first_name}, you come from the " f"{self.last_name} family. You currently reside in " f"{self.location}. Oh, I forgot to mention that you're " f"a {self.gender}. Have a nice day!")
但我觉得这种拼接多个f-string的写法不够整洁。我最初尝试用更自然的换行方式实现,代码如下,但无法正常运行:
def describe_user(self): print(f"User {self.first_name} {self.last_name} is a {self.gender} from {self.location}")
请问有没有更优的实现方式?
解决方案
以下几种方式可以让代码更整洁,同时保证正常运行:
1. 括号包裹多行f-string(Python 3.12+)
Python 3.12及以上版本支持直接用括号包裹多行f-string,无需拼接,写法更自然:
def describe_user(self): print(f"User {self.first_name} {self.last_name} is a " f"{self.gender} from {self.location}") # 或者3.12+支持的原生多行f-string: def describe_user(self): print(f"User {self.first_name} {self.last_name} is a {self.gender} from {self.location}")
2. 反斜杠换行
在每行末尾加反斜杠,保持字符串自然换行的同时避免语法错误:
def describe_user(self): print(f"User {self.first_name} {self.last_name} is a \ {self.gender} from {self.location}")
3. 先定义字符串变量再打印
对于较长的文本,先将字符串赋值给变量再打印,可读性更强:
def greet_user(self): greeting = ( f"Hello there {self.first_name}, you come from the " f"{self.last_name} family. You currently reside in " f"{self.location}. Oh, I forgot to mention that you're " f"a {self.gender}. Have a nice day!" ) print(greeting)
4. 三引号配合textwrap.dedent
想用三引号保留排版又不想有多余缩进时,可借助textwrap.dedent去除统一缩进:
import textwrap def greet_user(self): greeting = textwrap.dedent(f""" Hello there {self.first_name}, you come from the {self.last_name} family. You currently reside in {self.location}. Oh, I forgot to mention that you're a {self.gender}. Have a nice day! """).strip() print(greeting)
内容的提问来源于stack exchange,提问作者PastaSource
相关产品推荐
相关产品推荐

