Python 3.4“\n”无法在shell wind中执行字符串操作

2024-05-15 05:21:00 发布

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

在pythonshell中使用windows7和python3.4

import math
class Drink:

objInst = 0

def __init__(self, name:str, price:float, calories:float, total_fat:float, sodium:float, totalCarbs:float, fiberAmt:float, protein:float, sugars:float, companyID:str):
    Drink.objInst += 1
    self._id = math.fabs(math.fabs((5*3)-math.ceil(((Drink.objInst+1)*3*math.floor(price))/((price*7)**5))+(11**3)*2)/(math.log(1009/97)))*100
    self.name = name
    self.price = price
    self.cal = calories
    self.fatTotal = total_fat
    self.sodium = sodium
    self.carbTotal = totalCarbs
    self.fiber = fiberAmt
    self.protein = protein
    self.sugars = sugars
    self.compID = companyID
def getName(self):
    return self.name
def getPrice(self):
    return '${:.2f}'.format(self.price)
def getCalories(self):
    return '{:5.1f} calories'.format(self.cal)
def getTotalFat(self):
    return 'Total grams(g) of fat: {:4.1f}'.format(self.fatTotal)
def getSodium(self):
    return '{:5.1f} miligrams (mg)'.format(self.sodium)
def getCarbs(self):
    return 'Carbs: {:4.1f} grams(g)'.format(self.carbTotal)
def getFiberAmt(self):
    return '{:3.1f} grams(g)'.format(self.fiber)
def getProtein(self):
    return '{:3.1f} grams(g)'.format(self.protein)
def getSugar(self):
    return '{:4.1f} grams(g)'.format(self.sugars)
def getCompanyName(self):
    return 'Company ID belongs to {0}'.format(self.compID)

def getImportantProductInfo(self):
    return [self.price, self.cal, self.fatTotal]

def __str__(self):
    """human readable"""
    return "Name: {name} \n Price: {price}\nCalories: {cal}\nTotal fat in gramgs(g): {fat}\nSodium in milligrams(mg): {Na}\nCarbs: {carbs}g\nFiber: {fiber}g\nProtein: {protein}g\nSugar: {sugar}g\nCompany ID: {compID}g\n".format(name=self.name,price=self.price,cal=self.cal,fat=self.fatTotal,Na=self.sodium,carbs=self.carbTotal,fiber=self.fiber,protein=self.protein,sugar=self.sugars,compID=self.compID)

def __repr__(self):
    """code form"""
    return 'Drink({name},{price},{cal},{fat},{Na},{carbs},{fiber},{protein},{sugar},{compID})'.format(name=self.name,price=self.price,cal=self.cal,fat=self.fatTotal,Na=self.sodium,carbs=self.carbTotal,fiber=self.fiber,protein=self.protein,sugar=self.sugars,compID=self.compID)

是的。但是为什么不起作用(示例输出):

>>> javaChip = Drink('java chip',1.29, 500,2.3,350,5,2,1,45,'STARBUCKS')
>>> javaChip
Drink(java chip,1.29,500,2.3,350,5,2,1,45,STARBUCKS)
>>> str(javaChip)
'Name: java chip \n Price: 1.29\nCalories: 500\nTotal fat in gramgs(g): 2.3\nSodium in milligrams(mg): 350\nCarbs: 5g\nFiber: 2g\nProtein: 1g\nSugar: 45g\nCompany ID: STARBUCKSg\n'
>>> 

它应该像\n意味着换行一样打印出来,但我不明白为什么。 有人能解释一下吗?非常感谢。你知道吗


Tags: nameselfformatreturndefmathfloatfat
1条回答
网友
1楼 · 发布于 2024-05-15 05:21:00

在Windows中,所有用于显示字符串的方法都无法将\n解析为CR&LF对。这不是Windows的错——在Linux上也会看到同样的结果。你知道吗

我建议尝试print你的字符串。你知道吗

相关问题 更多 >

    热门问题