Python中的多行f字符串 [英] Multiline f-string in Python

查看:366
本文介绍了Python中的多行f字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write PEP-8 compliant code for a domestic project (I must admit that those are my first steps in the python world) and i've got a f-string that is more than 80 char long

-self.text点附近的实线是80个字符. (对不起没有预览的可悲链接,但我必须有10个以上的代表才能发布'em)

- the solid thin line near the dot at self.text is the 80 char mark. (Sorry for the sad link without preview but i must have 10+ rep to post 'em)

我正尝试以最 pythonic 的方式将其拆分为不同的行,但唯一有效的方法是对我的短绒毛狗报错

I'm trying to split it into different lines in the most pythonic way but the only aswer that actually works is an error for my 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

短毛绒认为我不尊重PEP-8的E122,有没有办法使字符串正确并符合代码?

The linter thinks that i'm not respecting E122 from PEP-8, is there a way to get the string right and the code compliant?

推荐答案

来自样式指南适用于Python代码:

包裹长行的首选方法是使用Python隐含的 括号,方括号和大括号内的行连续.

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

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

Given this, the following would solve your problem in a PEP-8 compliant way.

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

Python字符串在未用逗号分隔时会自动连接,因此您无需显式调用join().

Python strings will automatically concatenate when not separated by a comma, so you do not need to explicitly call join().

这篇关于Python中的多行f字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆