Question:
I’m trying to make a calendar that asks the user for their birthday and it shows the month that they were born with their birthday highlighted. But right now, it just highlights every instance of that number. Wondering if there’s a way to fix that. Repl link: https://replit.com/@hbrehm26/AP-Create-Task
The str.replace() command replaces every instance in a string.
If there are spaces around the number you want to highlight in the formatted calendar, you could replace the command:
It would already work for two-digit dates. The spaces just allow one-digit dates to be detected on their own, and not as part of a two-digit date.
Clarification:
Like already said here the problem with the str.replace() is that he replaces all instances of the substring, so you need to modifyto only target specific days.
What I do recommend here is for you to split the calendar into weeks and compile a regex to find the exact day. You can use \b in the regex to prevents partial matches and re.escape(str(d)) to escape the day number d.
So it would result in something like this:
def birthday(y, m, d):
# Creating the calendar
c = calendar.TextCalendar(calendar.SUNDAY)
calendar_str = c.formatmonth(y, m)
# Split the calendar
weeks = calendar_str.split('\n')
# Compile the regex
day_regex = re.compile(r'\b' + re.escape(str(d)) + r'\b')
# Process each week to find and replace the specific day with highlights
for i in range(len(weeks)):
if day_regex.search(weeks[i]):
weeks[i] = day_regex.sub("\033[91m" + str(d) + "\033[0m", weeks[i])
break
# Join the weeks back into a single string
highlighted_calendar_str = '\n'.join(weeks)
# Print the highlighted calendar
print()
print(highlighted_calendar_str)
This will not precisely solve the issue because in this approach you replace every instance of the day number in the calendar string, leading to the problem that op described.
You try to mitigate the issue by adding spaces around d , which will reduce incorrect matches… buuuut it will only work if d is neither at the beginning nor the end of a line, and it fails for single-digit days at the start or end of weeks because they might only have one space or be adjacent to other characters like newline characters.