我正在嘗試打印此函數(shù),但輸出帶有括號和引號......就像這樣('1', ',December', ',1984')def date_string(day_num, month_name, year_num): """ Turn the date into a string of the form day month, year """ date = str(day_num) , "," + month_name , "," + str(year_num) return dateprint(date_string(1, "December", 1984))
3 回答

侃侃爾雅
TA貢獻(xiàn)1801條經(jīng)驗 獲得超16個贊
date = str(day_num) , "," + month_name , "," + str(year_num)
使用此代碼,您創(chuàng)建的是元組而不是字符串。
要改為創(chuàng)建字符串,您有多種選擇:
date = '{} {},{}'.format(day_num, month_name, year_num) # Recommended method
或者
date = '%s %s, %s' % (day_num, month_name, year_num) # Fairly outdated
或者+
根據(jù)其他答案用于連接。使用+
字符串連接不是很理想,因為你必須確保你的每個操作數(shù)轉(zhuǎn)換為字符串類型。

PIPIONE
TA貢獻(xiàn)1829條經(jīng)驗 獲得超9個贊
問題是你有一些逗號,
需要加號+
:
date = str(day_num) , "," + month_name , "," + str(year_num)
這是創(chuàng)建一個元組而不是一個字符串。將其更改為:
date = str(day_num) + "," + month_name + "," + str(year_num)

阿晨1998
TA貢獻(xiàn)2037條經(jīng)驗 獲得超6個贊
創(chuàng)建變量時嘗試將 更改,為 a 。這將創(chuàng)建一個字符串而不是一個列表。+date
def date_string(day_num, month_name, year_num):
"""
Turn the date into a string of the form
day month, year
"""
date = str(day_num) + ", " + month_name + ", " + str(year_num)
return date
print(date_string(1, "December", 1984))
添加回答
舉報
0/150
提交
取消