Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re.sub not working
#8
This is not an issue of raw strings. Raw strings are used to prevent backslashes from being treated as escape sequences. An r"string" has no effect on parentheses. As you know, your problem was that re.sub() interpreted the parentheses in your regex strings as grouping characters instead of literal parentheses.

When a python program is compiled (converted to bytecodes) all strings are converted to raw strings (escape sequences are replaced with associated character(s)). Strings with an "r" prefix skip the escape sequence processing as they are already in "raw" form. Since all strings are "raw" strings when your program runs, there is no way, or no need, to convert a str to a "raw" str.

You don't want two loops in generator(). Replace the words as they are encountered.
def generator(text:str) -> str:
    '''find needed words in text and ask user enter them, then print result'''
    for placeholder in re.findall(r'_+\s?\([^\)]+\)', text):  # good spot for a raw string
        word_type = placeholder.replace('_', '').replace('(', '').replace(')', '').replace('\n', ' ')
        text = text.replace(placeholder, input(f'Please input a(n) {word_type}\n'), 1)
    print(text)
This is a wonderful example of simpler is better. The dictionary in your solution limits your madlib to one noun, one verb, one adjective, etc. I suppose you could have verb2 and noun3, but that either looks clunky (Enter a verb2) or requires extra processing to remove the extra sequence number. It is much easier to replace the placeholders as they are encountered. With no dictionary you don't have to worry about uniqueness. Your madlib can have 10 nouns, because your program only knows about the next noun.
Reply


Messages In This Thread
re.sub not working - by Ryokousha - Oct-02-2022, 04:18 AM
RE: re.sub not working - by deanhystad - Oct-02-2022, 04:50 AM
RE: re.sub not working - by Coricoco_fr - Oct-02-2022, 05:42 AM
RE: re.sub not working - by Ryokousha - Oct-02-2022, 07:06 AM
RE: re.sub not working - by Ryokousha - Oct-02-2022, 07:04 AM
RE: re.sub not working - by Pedroski55 - Oct-02-2022, 05:59 AM
RE: re.sub not working - by snippsat - Oct-02-2022, 11:34 AM
RE: re.sub not working - by deanhystad - Oct-02-2022, 03:00 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020