'Using python method string.replace() to replace the names of the day weeks with custom string(ex: monday = day1/firstday/montag)
I just started learning python and I'm working on a personal mini project in which I want to print with as little code as possible a certain string depending on the date the user enters. (ex: monday = day1/firstday/montag)
import datetime
from datetime import datetime
import calendar
my_answer = input("Enter date: (yyyy-mm-dd) ")
my_date = datetime.strptime(my_answer, "%Y-%m-%d")
year, week_num, day_of_week = my_date.isocalendar()
day_name = calendar.day_name[my_date.weekday()]
new_day = day_name.replace("Monday", "Day 1")
#new_day = day_name.replace("Tuesday", "Day 2")
# new_day = day_name.replace("Wednesday", "Day 3")
# new_day = day_name.replace("Thursday", "Day 4")
# new_day = day_name.replace("Friday", "Day 5")
# new_day = day_name.replace("Saturday", "Day 6")
# new_day = day_name.replace("Sunday", "Day 7")
print( "The date " + str(my_answer) + " is " + new_day + " of the week " + str(week_num))
Solution 1:[1]
You need re.sub
import re
string = 'Monday aaj montag nahi kal tha usko day1 ya firstdaybhi bolsakte hain'
new_string = re.sub(r'day1|firstday|montag', 'Monday', string)
print(new_string)
r'day1|firstday|montag' is just a regular expression. You can read more about it here https://docs.python.org/3/library/re.html
Solution 2:[2]
In your code, there is not much to change. But, I highly suggest you use dateutil object in order to parse the input date:
from dateutil.parser import parse
# Rest of the code
my_date = parse(input("Enter date: (yyyy-mm-dd) "))
# Rest of the code
parse is a function that automatically reformats date-strings into date objects. Meaning, you do not need to define the date patter ("%Y-%m-%d"). Also, if you put a string like My date is as what follows: 1998-07-08, it finds the date ("1998-07-08") intelligently.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nikhil Devadiga |
| Solution 2 | Amirhossein Kiani |
