#๐Ÿ”’ How to properly combine F strings and raw strings with () and regex?

23 messages ยท Page 1 of 1 (latest)

signal blaze
#

what I am trying to achieve:

country = "United States (USA)"
out = rf"<title>{country} ([\d\.]*.?)</title>"

I want the above to give me
out = rf"<title>United States \(USA\) ([\d\.]*.?)</title>"
but it does not escape the parentheses.

When I try

country = "United States \(USA\)"
out = rf"<title>{country} ([\d\.]*.?)</title>"

I instead get
out = rf"<title>United States \\(USA\\) ([\d\.]*.?)</title>"

lyric depotBOT
#

@signal blaze

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.

soft valve
#

!e

country = "United States \(USA\)"
out = rf"<title>{country} ([\d\.]*.?)</title>"
print(out)
lyric depotBOT
soft valve
#

Ignore the warning, the print is the third line

#

As you can see there's only one slash

#

That's because in \\ The first slash is used to escape the second one

#

So overall you get one slash

quasi hare
#

re.escape is from the re module, and escapes a string so that it can be used in a regepx to match that string.

#

... and it sounds like you might be confusing the escaped nature of the rendering of the string from its actual contents.

How are you displaying the resulting value in out?

soft valve
meager wing
soft valve
#

But yes, re.escape is a good option

quasi hare
soft valve
#

if you don't know what the string contains then yeah

signal blaze
#

ah Iโ€™ll just use re.escape

#

I am providing all the strings but Iโ€™d rather not edit all of them to have backslashes

quasi hare
#

Always better to provide the strings in the pure form, and let a computer mangle them to go inside a regexp ๐Ÿ™‚ Computers don't get bored.

lyric depotBOT
#
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.