Owl*_*lzy 43 python string python-3.6
我正在尝试为国内项目编写符合PEP-8的代码(我必须承认这些是我在python世界中的第一步)并且我有一个超过80个字符长的f字符串
- self.text上点附近的实线是80个字符.(抱歉没有预览的悲伤链接,但我必须有10+代表发布'em)
我试图把它分离成在最不一样的行Python的方式,但实际工作的唯一aswer是我棉短绒错误
工作守则:
def __str__(self):
return f'{self.date} - {self.time},\nTags:' + \
f' {self.tags},\nText: {self.text}'
Run Code Online (Sandbox Code Playgroud)
输出:
2017-08-30 - 17:58:08.307055,
Tags: test tag,
Text: test text
Run Code Online (Sandbox Code Playgroud)
linter认为我不尊重PEP-8中的E122,有没有办法让字符串正确并符合代码?
nod*_*ddy 30
包装长行的首选方法是在括号,方括号和花括号内使用Python的隐含行连续性。
鉴于此,以下将以符合PEP-8的方式解决您的问题。
return (
f'{self.date} - {self.time}\n'
f'Tags: {self.tags}\n'
f'Text: {self.text}'
)
Run Code Online (Sandbox Code Playgroud)
当不使用逗号分隔时,Python字符串将自动连接,因此您无需显式调用join()。
lmi*_*asf 27
您可以使用三重单引号或三重双引号,但在字符串的开头放置一个 f:
return f'''{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}'''
Run Code Online (Sandbox Code Playgroud)
return f"""{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}"""
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要使用“\n”,因为您使用的是多行字符串。
Jor*_*ley 22
我想是的
return f'''{self.date} - {self.time},
Tags: {self.tags},
Text: {self.text}'''
Run Code Online (Sandbox Code Playgroud)
cod*_*ior 16
正如@noddy 所提到的,该方法也适用于变量赋值表达式:
var1 = "foo"
var2 = "bar"
concat_var = (f"First var is: {var1}"
f" and in same line Second var is: {var2}")
print(concat_var)
Run Code Online (Sandbox Code Playgroud)
应该给你:
First var is: foo and in same line Second var is: bar
Run Code Online (Sandbox Code Playgroud)
Tim*_*and 11
您可以混合多行引用样式以及常规字符串和 f 字符串:
foo = 'bar'
baz = 'bletch'
print(f'foo is {foo}!\n',
'bar is bar!\n',
f"baz is {baz}!\n",
"not f-string version: baz is {baz}!\n",
'''bletch
is
bletch!''')
Run Code Online (Sandbox Code Playgroud)
打印此内容(注意缩进):
foo is bar!
bar is bar!
baz is bletch!
not f-string version: baz is {baz}!
bletch
is
bletch!
Run Code Online (Sandbox Code Playgroud)