str.replace() when str contains \

MRAB python at mrabarnett.plus.com
Sat Oct 29 20:25:32 EDT 2022


On 2022-10-29 19:21, Bernard LEDRU 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
> 
In a plain string literal, \ followed by 1..3 of the digits 0..7 is an 
octal (base 8) escape sequence, and \ followed by 'a' is the bel 
character, so '\7' == '\07' == '\007' == '\a' == '\x07'.


More information about the Python-list mailing list