python格式化代码是什么意思_Python代码格式化

4 个答案:

答案 0 :(得分:13)

多行字符串更具可读性:

def __str__(self):

return '''\

Car Type

mpg: %.1f

hp: %.2f

pc: %i

unit cost: $%.2f

price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price)

要保持视觉上有意义的缩进级别,请使用textwrap.dedent:

import textwrap

def __str__(self):

return textwrap.dedent('''\

Car Type

mpg: %.1f

hp: %.2f

pc: %i

unit cost: $%.2f

price: $%.2f'''% (self.mpg,self.hp,self.pc,self.cost,self.price))

答案 1 :(得分:6)

您可以通过将表达式放在括号中来解决问题:

def __str__(self):

return ("Car Type \n"+"mpg: %.1f \n" % self.mpg +

"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc +

"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price))

但是,我会考虑更像这样写:(代码未经测试)

def __str__(self):

return """\

Car Type

mpg: %(mpg).1f

hp: %(hp).2f

pc: %(pc)i

unit cost: $%(cost).2f

price: $%(price).2f """ % self.__dict__

答案 2 :(得分:4)

Python不允许你在这样的表达式中结束一行;最简单的解决方法是用反斜杠结束该行。

def __str__(self):

return "Car Type \n"+"mpg: %.1f \n" % self.mpg + \

"hp: %.2f \n" %(self.hp) + "pc: %i \n" %self.pc + \

"unit cost: $%.2f \n" %(self.cost) + "price: $%.2f "%(self.price)

在这种情况下,反斜杠必须是该行的最后一个字符。从本质上讲,它意味着“忽略这里有换行的事实”。换句话说,你正在逃避换行,因为它通常会是一个重大的突破。

您可以随时使用反斜杠转义其他重要换行符。这很愚蠢,但你甚至可以做到

def foo():

return \

1

以便foo()返回1.如果没有那里有反斜杠,则1本身会导致语法错误。

答案 3 :(得分:3)

它需要一些额外的设置,但数据驱动的方法(具有良好的垂直对齐剂量)很容易随着项目的发展而变化和修改。它间接消除了长行代码的问题。

def __str__(self):

dd = (

("Car Type %s", ''),

(" mpg: %.1f", self.mpg),

(" hp: %.2f", self.hp),

(" pc: %i", self.pc),

(" unit cost: $%.2f", self.cost),

(" price: $%.2f", self.price),

)

fmt = ''.join("%s\n" % t[0] for t in dd)

return fmt % tuple(t[1] for t in dd)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值