python输出多行字符串_Python中的多行f字符串

本文探讨了在遵循PEP-8编码规范的情况下,如何优雅地处理超过80字符的f-string。作者分享了一个示例,通过使用Python的括号内隐式行连接来解决这个问题,确保代码的可读性和合规性。解决方案中,长字符串被拆分成多行,每行以f''开头,并通过空格连接,避免了语法错误和linter警告。
摘要由CSDN通过智能技术生成

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

- 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)

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

Working Code:

def __str__(self):

return f'{self.date} - {self.time},\nTags:' + \

f' {self.tags},\nText: {self.text}'

Output:

2017-08-30 - 17:58:08.307055,

Tags: test tag,

Text: test text

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?

解决方案The preferred way of wrapping long lines is by using Python's implied

line continuation inside parentheses, brackets and braces.

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 strings will automatically concatenate when not separated by a comma, so you do not need to explicitly call join().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值