Python replace multiple strings (m*n) combination

Erik python at lucidity.plus.com
Fri Feb 24 16:44:16 EST 2017


On 24/02/17 18:54, kar6308 at gmail.com wrote:
> for example is the search string is not a variable we can say
>
> re.search(r"\$%^search_text", "replace_text", "some_text") but when I
> read from the dict where shd I place the "r" keyword, unfortunately
> putting inside key doesnt work "r key" like this....

Do you mean the 'r' that is in front of the first argument to 
re.search()? If not, ignore this response ;)

If so, then you need to understand what "raw string" literals are. They 
are a construct that the *parser* understands in order to build a string 
based on what is between the quotation marks.

The prefix 'r' on a string literal just means that certain characters 
(such as '\') will not be treated specially in the way they are for 
regular string literals.

In your case, r"\$%search_text" is the same as "\\$%search_text". In the 
second case, because it's a regular string literal where the backslash 
is important, the backslash needs to be escaped (with a leading 
backslash) - otherwise the parser thinks that backslash is itself an 
escape character. You can try all of this at the Python REPL shell:

Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
 >>> r"\$%search_text"
'\\$%search_text'
 >>> "\\$%search_text"
'\\$%search_text'

The two string objects that exist at runtime (which are the things 
printed out) are the same regardless of how you express them in the 
source code.

Therefore, you don't need to do anything with 'r' inside your key - if 
it's not expressed in Python source code, then the "raw" prefix does not 
come into it.

Regards, E.



More information about the Python-list mailing list