str.replace() when str contains \

Barry barry at barrys-emacs.org
Sat Oct 29 17:27:38 EDT 2022



> On 29 Oct 2022, at 22:14, Bernard LEDRU <python at bernardledru.be> wrote:
> 
> Hello,
> 
> https://docs.python.org/3/library/stdtypes.html#string-methods
> 
> str.replace(old, new[, count])¶
> Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
> 
> Attention when the string contains the escape character.
> 
> Consider :
> 
>>>> a="H:\2023"; print(a.replace("\\","/"))
> H:3
>>>> a="H:\a2023"; print(a.replace("\\","/"))
> H:2023
>>>> a="H:\_2023"; print(a.replace("\\","/"))
> H:/_2023

String a does not quote the \ after :.
You need “H:\\2023” etc. check what a is before the replace with a
print(repr(a))

Barry

> 
> Best regards,
> Bernard LEDRU
> -- 
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list