Python中的多行fstring

2024-05-19 14:00:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一个国内项目编写符合PEP-8的代码(我必须承认,这是我在python世界中的第一步),我得到了一个长度超过80个字符的f字符串

-self.text点附近的实线细线是80字符标记

我正试图用最具pythonic的方式将它分成不同的行,但唯一有效的方法是我的linter出现了一个错误

工作代码:

def __str__(self):
    return f'{self.date} - {self.time},\nTags:' + \
    f' {self.tags},\nText: {self.text}'

输出:

2017-08-30 - 17:58:08.307055,
Tags: test tag,
Text: test text

linter认为我不尊重PEP-8中的E122,有没有办法使字符串正确并且代码兼容


Tags: 项目字符串代码text标记testselflinter
3条回答

您可以使用三重单引号或三重双引号,但在字符串开头加上f:

三重单引号

return f'''{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}'''

三重双引号

return f"""{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}"""

请注意,您不需要使用“\n”,因为您使用的是多行字符串。

我想是的

return f'''{self.date} - {self.time},
Tags: {self.tags},
Text: {self.text}'''

Style Guide for Python Code

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.

鉴于此,以下内容将以符合PEP-8的方式解决您的问题

return (
    f'{self.date} - {self.time}\n'
    f'Tags: {self.tags}\n'
    f'Text: {self.text}'
)

Python字符串在没有逗号分隔时将自动连接,因此不需要显式调用join()

相关问题 更多 >