Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

direct output of variable and through print() are different

Suppose I have string

S = '\\\\Serial\\file'

Output:

S

'\\\\Serial\\file'


print(s)

\\Serial\file

So the question is what is the reason print function truncate the backslashes ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But still why it remove two backslashes from front and just one from last? what could be the reason? and why its removing?

Also it dont gives ‘ ‘ is that any meaning or use?

>Solution :

In a python string \ is a character which is combined with another character is order to define a special character.

For example, the string \n represents a new line, instead of the actual backslash n. So why is this important? Because then to indicate a backslash you actually need two backslashes. The first one indicates the special string and the second indicates the actual backslash. Therefore every two backslashes is one backslash when printed. That’s why the first four backslashes become two (4/2 = 2) and the second ones become one (2/2 = 1). If you want to indicate the raw string, you can indicate it with an r, i.e.

s = r"\\test"

which will print as typed.

As for the missing ‘, those just indicate the beginning or end of a string, when printing, everything is converted to a string and the ‘ are omitted.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading