我正在尝试为我正在选修的课程解决这个样本练习,问题是:
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
我做错了什么?
提前感谢
发布于 2015-09-16 00:27:52
你的代码是错误的,而且效率很高,为什么你不使用str.replace?:
>>> "29-04-1974".replace('-','/')
'29/04/1974'发布于 2015-09-16 00:35:34
或者,您可以使用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。发布于 2015-09-16 00:40:23
出什么问题了:
您的重新格式化函数从不使用x作为输入。
另外,replace是更简单、更正确的解决方案。
https://stackoverflow.com/questions/32591088
复制相似问题