Regular Expression Issues

Ok, so I have a semi-destructive problem with re.sub.

Take the following code:

import re
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = r'C:\foobar'
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s

I would think that would give me:

somefile.exe -i C:\\foobar

But instead he gives me:

somefile.exe -i C:♀oobar

I know that \ f is an escape char, but even if I try to do it in such a way that special characters should be avoided. Even if I do this:

print r'%s' % s

This still gives me the following:

somefile.exe -i C:♀oobar

Why is he doing this? And what is the best way to avoid this?

Edit Ninja:

If I look at the value of s, this is:

'somefile.exe -i C:\x0coobar'

Why \ f turned into \ x0. Ugh.

Edit:

One more question if I modify the code:

import re
import os
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = os.path.abspath(r'C:\foobar')
some_str
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s

Gives me:

>>> import re
>>> import os
>>> str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>> some_str = os.path.abspath(r'C:\foobar')
>>> some_str
'C:\\foobar'
>>> s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
>>> print s
somefile.exe -i C:♀oobar

Now why. Since os.path.abspath is running away. Why is re.sub still confused?

, . string.replace - , .

, . .

+3
4

\f - . , :

some_str = r'C:\\foobar'

:

s = re.sub(r'<INPUT>', some_str.encode("string_escape"), str_to_be_subbed)
+3

:

print str_to_be_subbed.replace("<INPUT>",some_str)

:

repl ; , .

+3

Python, ...

re.sub(pattern, repl, string, count = 0, flags = 0) , repl. , . repl ; , . \n , \r .. escape-, \j,

"C: ♀oobar".

, .

, .

>>>import re
>>>str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>>some_str = r'C:\foobar'
>>>s = re.sub(r'\<INPUT\>', lambda _:some_str, str_to_be_subbed)
>>>print s
somefile.exe -i c:\foobar
+2

, str.replace():

>>> str_to_be_subbed.replace('<INPUT>',some_str)
'somefile.exe -i C:\\foobar'
>>> 
0

Source: https://habr.com/ru/post/1708887/


All Articles