#πŸ”’ πŸ”’ Python Find and Replace using Backreference and Variable

14 messages Β· Page 1 of 1 (latest)

frigid kernel
#

Please help on the below to get mentioned output using "re.sub"

import re year = '2025' source = '<publicationyear first=""/>' source = re.sub(r"(<publicationyear first=\")(\"/>)", fr"\1{year}\2", source) print(source)

Needed output: <publicationyear first="2025"/>

Tried in many sites but didn't get solutions with the combination of backreference and variable replacement.

glad mothBOT
#

@frigid kernel

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

paper dew
#

re.sub is the wrong tool for this, however if you have to use it because this is some sort of question/assignment, you can fix the regex engine being confused by using the long form for group references in substitution strings: rf"\g<1>{year}\g<2>"

#

The way I would recommended doing this, assuming source is static, is by f"{source[:24]}{year}{source[24:]}"

#

Also minor nitpick, but you should use rf instead of fr, since it is read as "raw f-string".

frigid kernel
#

please tell me what is the meaning of "[:24]"

paper dew
#

It's a slice. Normal indexing is [index], but adding a : does [start:end]. Omitting either start or end assumes you want the slice to continue all the way, so [:24] is saying "give me the substring from the start to index 23", and [24:] is saying "give me the substring from index 24 to the end.

#
>>> source = '<publicationyear first=""/>'
>>> print(source[:24])
<publicationyear first="
>>> print(source[24:])
"/>
frigid kernel
#

Than you so much. Very well explained. helped a lot.
Thanks friend.

glad mothBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

πŸ”’ Python Find and Replace using Backreference and Variable

glad mothBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.