我正在尝试打印此函数,但输出带有括号和引号......就像这样('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贡献1801条经验 获得超16个赞
date = str(day_num) , "," + month_name , "," + str(year_num)
使用此代码,您创建的是元组而不是字符串。
要改为创建字符串,您有多种选择:
date = '{} {},{}'.format(day_num, month_name, year_num) # Recommended method
或者
date = '%s %s, %s' % (day_num, month_name, year_num) # Fairly outdated
或者+
根据其他答案用于连接。使用+
字符串连接不是很理想,因为你必须确保你的每个操作数转换为字符串类型。

PIPIONE
TA贡献1829条经验 获得超9个赞
问题是你有一些逗号,
需要加号+
:
date = str(day_num) , "," + month_name , "," + str(year_num)
这是创建一个元组而不是一个字符串。将其更改为:
date = str(day_num) + "," + month_name + "," + str(year_num)

阿晨1998
TA贡献2037条经验 获得超6个赞
创建变量时尝试将 更改,为 a 。这将创建一个字符串而不是一个列表。+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
提交
取消