'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 1:[1]
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)
Solution 2:[2]
Writing code by your logic, initialize a list
of months
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
Now iterate over all the words in the string and check if that word is in the months
list.
newLine = ""
for word in line.split():
if word in months:
newLine += "("
newLine += word + " "
Now at the end, remove the trailing space and append the closing bracket
newLine = newLine[:-1]
newLine += ")"
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 | Tim Biegeleisen |
Solution 2 | Geeky Quentin |