str.replace() when str contains \
Thomas Passin
list1 at tompassin.net
Sat Oct 29 18:14:49 EDT 2022
Better to use raw strings whenever backslashes are involved.
On 10/29/2022 2:21 PM, 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
These examples actually produce an "H" with a symbol after it, a
different symbol for each. Probably the message posting system can't
display it, but I see it in a python terminal session on Windows. So
the first a="H:\2023" example produces "Hx", where x is some symbol.
Since there is no backslash, no character gets replaced. IOW,
a="H:\2023"; print(a)
and
a="H:\2023"; print(a.replace("\\","/"))
print the same thing.
>>>> a="H:\_2023"; print(a.replace("\\","/"))
> H:/_2023
What did you expect or want to happen?
More information about the Python-list
mailing list