-1

I am trying to replace two lists a text:

text = "today is friday july 1 2018"

days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
daysRegex = re.compile('|'.join(map(re.escape, days)))

months =  ['january', 'february', 'march', 'april', 'may', 'mai', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
monthsRegex = re.compile('|'.join(map(re.escape, months)))

replaces = daysRegex.sub("<day>", text) and monthsRegex.sub("<month>", text) 

print(replaces)

output:

today is friday < month> 1 2018

correct output:

today is < day> < month> 1 2018

I'm not sure I'm using the and operator correctly. I'm just trying to put into practice what I studied about it (but I may have misunderstood)

marin
  • 923
  • 2
  • 18
  • 26

2 Answers2

2

Since you need to replace 2 value you can do..

Demo:

import re
text = "today is friday july 1 2018"

days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
daysRegex = re.compile('|'.join(map(re.escape, days)))
months =  ['january', 'february', 'march', 'april', 'may', 'mai', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
monthsRegex = re.compile('|'.join(map(re.escape, months)))
replaces = daysRegex.sub("<day>", monthsRegex.sub("<month>", text))

print(replaces)

or

text = monthsRegex.sub("<month>", text)
replaces = daysRegex.sub("<day>", text)
print(replaces)

Output:

today is <day> <month> 1 2018
Rakesh
  • 81,458
  • 17
  • 76
  • 113
2

You indeed misuse the and operator, I suggest reading this post to understand your error: Using "and" and "or" operator with Python strings

You should be applying the second sub on the result of the first one such as follows :

replaces = daysRegex.sub("<day>", monthsRegex.sub("<month>", text))

You will get the correct output then.

d6bels
  • 1,432
  • 2
  • 18
  • 30