在Python上重新格式化日期

时间:2015-09-15 16:25:16

标签: python string join replace split

我正在尝试为我正在上课的这个示例练习解决,问题是:

Define function reformat which replaces all occurrences of "-" with "/" in a string. Once defined, your function should work like this:

new = reformat("29-04-1974")
print(new)
"29/04/1974"

我对python不太熟悉,但提出了以下内容:

date = "29", "04", "1974"
new = reformat("29-04-1974")
def reformat(x):
    x = ("%s" "%s" "%s" % date).split("-") 
    return x

p = "/".join(reformat("%s" "%s" "%s" % date))

print (p)

打印:29041974

我做错了什么?

提前致谢

3 个答案:

答案 0 :(得分:3)

您的代码错误且效率很高,为什么您不使用str.replace? :

>>> "29-04-1974".replace('-','/')
'29/04/1974'

答案 1 :(得分:1)

或者您可以使用datetime函数:

from datetime import datetime

dt = datetime.strptime('29-04-1974', '%d-%m-%Y')  # parse the string into 
                                                  # a datetime object
print(dt.strftime('%d/%m/%Y'))                    # format the datetime
如果您改变主意,了解如何显示日期,

将为您提供很大的灵活性。

您的功能有什么问题:

  • 您没有使用(阅读)您要作为参数传递的x。该函数始终使用您事先定义的date
  • 您创建的字符串不包含-,但希望在每个-分割。
  • "%s" "%s" "%s" % date会转换为"%s%s%s" % date,这是您案例中的字符串29041974

答案 2 :(得分:0)

出了什么问题:

您的重新格式化功能从不使用x作为输入。

此外,替换是更简单和正确的解决方案。