我在处理代码战中的卡塔时遇到了麻烦。kata的目标是从日期格式中删除时间(我将在下面列出说明)。我使用的方法是索引拼接,删除逗号后的所有内容(这是时间所在的位置)。我正在用Python版本3.8编写此代码
You're re-designing a blog and the blog's posts have the following format for showing the date and time a post was made:
Weekday Month Day, time e.g., Friday May 2, 7pm
You're running out of screen real estate, and on some pages you want to display a shorter format, Weekday Month Day that omits the time.
Write a function,
shortenToDate
, that takes the Website date/time in its original string format, and returns the shortened format.Assume
shortenToDate
's input will always be a string, e.g. "Friday May 2, 7pm". AssumeshortenToDate
's output will be the shortened string, e.g., "Friday May 2".
代码:
def shorten_to_date(long_date):
#your code here
new_date = long_date[:-5]
print(new_date)
我使问题变得比看起来更难,主要问题之一是我一直调用print而不是返回函数。另一个错误是我想使用index而不是仅仅使用
rsplit()
删除逗号后面的所有内容并非所有的字符串都有相同的长度,因此最好只使用逗号分隔并返回第一个字符串
如果您确实需要使用索引,您可以在每个字符串中找到逗号的索引,并使用它对其进行切片
相关问题 更多 >
编程相关推荐