How to append parenthesis to the string text in python?

I have one string like "Article created on March 03 2021 for the some user"

I want to convert that string to "Article created on (March 03 2021 for the some user)" so I thought I should create a list containing all the name of the months, and then scan the string and if any month found then it should add starting parenthesis "(" to the left of the month’s name and another closing parenthesis ")" at the end of the string.

How can I achieve this?

>Solution :

We can try using re.sub here:

inp = "Article created on March 03 2021 for the some user"
output = re.sub(r'(\w+ \d{2} \d{4}\b.*)', r'(\1)', inp)
print(output)  # Article created on (March 03 2021 for the some user)

Leave a Reply