簡體   English   中英

output 中的括號

[英]Parentheses in output

我無法擺脫 output 中的括號。 我已經將 Visual Studio Code 中 python 的默認版本從 2.7 更改為 3.9。 我還將其中一個打印命令更改為返回命令。 任何其他建議將不勝感激。 這是代碼:

def build_car(year, color, make, model, *car_accessories): 
    print(f"This car is a {year} {color} {make} {model}  with the following accessories--:") 
    for accessory in car_accessories: 
        return (f"{car_accessories}")

car = build_car('2021', 'tan' ,'ford','focus',
                'leather seats',
                'tinted windows',
                'all wheel drive') 
print(car)

問題是*car_accessories是一個元組,當您打印該元組時,它會使用括號括起來。 您總是可以使用類似下面的方法將元組轉換為字符串。 獲得字符串后,您可以使用 f 字符串應用所需的任何格式。

return ', '.join(car_accessories)

build_car無法下定決心。 它打印一些東西,返回其他東西供調用者打印。 非常混亂。 如果 function 的作用只是格式化字符串,則其用途更廣泛。 讓調用者決定下一步如何處理它。 由於car_accessories是項目的元組,您可以用逗號“加入”它們。 整個格式化步驟可以用一個 f-string 完成。

def build_car(year, color, make, model, *car_accessories):     
    return f"""This car is a {year} {color} {make} {model} with the following accessories:
{", ".join(car_accessories)}
"""

car = build_car('2021', 'tan' ,'ford','focus',
                'leather seats',
                'tinted windows',
                'all wheel drive')
print(car)

您應該在 function 中構建完整的描述並返回完成的產品。 在 function 和調用程序之間拆分打印很尷尬。

def build_car(year, color, make, model, *car_accessories): 
    description = f"This car is a {year} {color} {make} {model}  with the following accessories: "
    description += ' '.join(car_accessories)
    return description

car = build_car('2021', 'tan' ,'ford','focus',
                'leather seats',
                'tinted windows',
                'all wheel drive') 
print(car)

Output:

This car is a 2021 tan ford focus  with the following accessories: leather seats tinted windows all wheel drive

您的原始代碼也有一個問題,即它一碰到第一個附件就return s 。 請查看return的工作原理,以免您再次犯此錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM