1

I am totally confused with the escape characters in Python. Sometimes I expect it to output one single '/', it prints '//'; Sometimes I use '//' as '/' it works, but other times it doesn't; And so on so on...

Some example:

print('\\hello') #output --> \hello
print(['\\hello']) #output --> ['\\hello']

So how should I understand '\hello', as '\hello' or '\\hello'? Can anyone explain the mechanism of escape characters more generally?

Bicheng
  • 687
  • 8
  • 20
  • Note that your second output also has string quotes: it’s being printed so as to match your _input_ (which is sometimes but not always what you want), so it has the same doubled backslashes. – Davis Herring Apr 01 '18 at 02:36

1 Answers1

2

Firstly there is the question of getting the right characters into your strings. Then there is the question of how Python displays your string. The same string can be displayed in two different ways.

>>> s = '\\asd'
>>> s
'\\asd'
>>> print(s)
\asd

In this example the string only has one slash. We use two slashes to create it but that results in a string with one slash. We can see that there's only one slash when we print the string.

But when we display the string simply by typing s we see two slashes. Why is that? In that situation the interpreter shows the repr of the string. That is it shows us the code that would be needed to make the string - we need to use quotes and also two slashes on our code to make a string that then has one slash (as s does).

When you print a list with a string as an element we will see the repr of the string inside the list:

>>> print([s])
['\\asd']
Oscar Benjamin
  • 12,649
  • 1
  • 12
  • 14