Simple question - end a raw string with a single backslash ?

Mladen Gogala mgogala at yahoo.com
Sat Oct 17 17:03:26 EDT 2020


On Thu, 15 Oct 2020 21:30:15 +0000, Stefan Ram wrote:

> Tony Flury <tony.flury at btinternet.com> writes:
>> >>> a = r'end' + chr(92)
> 
>   Or maybe,
> 
> a = r'''
> end\
> '''[ 1: -1 ]
> 
>   ? The first and the last line are messy, but in the middle,
>   the intended string is clearly visible.


You can use perl module for python. It is installable by pip.
Perl has no problems with handling backslashes.

https://pypi.org/project/perl/

What you need is something like this:

mgogala at umajor:~$ perl -e '$a="abcd";$a=~s/$/\\/; print "$a\n";'
abcd\

Python has a problem with backslashes:

Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> a="abcd"
>>> b=re.sub('$',chr(28),a)
>>> b
'abcd\x1c'

>>> b=re.sub('$',chr(0x41),a)
>>> b
'abcdA'
>>> b=re.sub('$','Z',a)
>>> b
'abcdZ'
>>> b=re.sub('$',chr(0x1C),a)
>>> b
'abcd\x1c'
>>> 

Any other character is shown as it should be, except backslash.





-- 
Mladen Gogala
Database Consultant
http://mgogala.byethost5.com


More information about the Python-list mailing list