why unexpected output in interpreter while using slashes \\ ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

why unexpected output in interpreter while using slashes \\ ?

I am trying to replace the / with \ input : "a/b/c/d" expected output : "a\b\c\d" my attempt : >>> text=r"a/b/c/d" >>> x=text.replace("/","\\") >>> x 'a\\b\\c\\d' working fine in script mode then why diffrent behaviour in interpreter ? how to print expected output in interpreter ?

24th Jun 2021, 5:15 PM
Ratnapal Shende
Ratnapal Shende - avatar
3 Answers
+ 6
this is a try with the console: using just the variable name, repr is internally used to output. if print() is used, output is the same as in interpreter. to get the expected output use print(repr(x)). using print(x) in console and in interpreter will give the same result. >>> x='\\a\\b\\c' >>> x '\\a\\b\\c' >>> print(x) \a\b\c >>> this is the description of repr: repr(object)Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.
24th Jun 2021, 5:35 PM
Lothar
Lothar - avatar
+ 2
Lothar means interpreter uses repr() to display object ? >>> x = "a\\b\\c\\d" >>> x 'a\\b\\c\\d >>> print(x) a\b\c\d\ still I don' t understand the diffrnce between print(x) and x what is happening internally? >>> repr("a\\b\\c\\d") " 'a\\\\b\\\\c\\\\d' " what is the case here ? str.replace("/", "\\") here, what is going inside replace() func only one backslash \ or two backslashes \\
24th Jun 2021, 6:00 PM
Ratnapal Shende
Ratnapal Shende - avatar
+ 2
yes, interpreter use repr() to display objects: that's why string are quote enclosed ;) if you try to replace one slash with two backslashes, you will get an error because the backslashe escape the closing quote (wich then is part of the string) and you don't provide another one closing quote... until you prefix the string with 'r' to get a raw string (without escape char): str.replace("/",r"\") but interpreter will still show you two backslashes until you explicitly print the string ^^
24th Jun 2021, 10:44 PM
visph
visph - avatar