输出带有括号和引号

时间:2019-03-02 08:57:52

标签: python

嗨,我正在尝试打印此功能,但是输出带有括号和引号...像这样

  

('1',',12月',',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 date
print(date_string(1, "December", 1984))

4 个答案:

答案 0 :(得分:1)

date = str(day_num) , "," + month_name , "," + str(year_num)

使用此代码,您将创建一个元组而不是字符串。

要创建一个字符串,您有多种选择:

date = '{} {},{}'.format(day_num, month_name, year_num) # Recommended method

OR

date = '%s %s, %s' % (day_num, month_name, year_num) # Fairly outdated

根据其他答案,或使用+进行串联。使用+进行字符串连接并不理想,因为必须确保将每个操作数转换为字符串类型。

答案 1 :(得分:0)

问题是您需要一些逗号,,并在其中加上加号+

    date = str(day_num) , "," + month_name , "," + str(year_num)

这将创建一个元组而不是字符串。更改为:

    date = str(day_num) + "," + month_name + "," + str(year_num)

答案 2 :(得分:0)

在创建变量,时,尝试将+更改为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))

答案 3 :(得分:0)

如果您使用的是3.6版或更高版本的Python,则可以按照以下方式为该任务使用所谓的f字符串

def date_string(day_num, month_name, year_num):
    date = f"{day_num},{month_name},{year_num}"
    return date
print(date_string(1, "December", 1984)) #output: 1,December,1984

请记住,它不适用于旧版本的Python,因此请在使用前检查您的版本。如果您想进一步了解f字符串,请阅读this article

相关问题