0

I have some questions about understanding raw string and repr(). So I tried thisin shell:

a=r'\\'
>>> len(a)
2
>>> str(a)
'\\\\'
>>> repr(a)
"'\\\\\\\\'"

I understand with the r, backslashes are treated as literal. But what is the reason that repr(a) comes "'\\\\'" as a result?

Olivia
  • 1
  • 2

3 Answers3

2

You're viewing the repr result in the interactive interpreter, which prints out the repr of the results. You are therefore seeing repr(repr(a)), which contains eight backslashes.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
1

r'\\' is a two-character string composed of \ and \. repr() gets its representation as a Python string literal. As backslashes start escape sequences in string literals, they themselves need to be escaped to accurately reproduce the original string, so repr() returns '\\\\' – a string composed of six characters. Finally, when displaying this string, the Python interactive shell itself uses repr(), which selects double quotes to avoid having to escape the ' in the string it’s trying to represent, and escapes each of the backslashes again, resulting in what you see.

  • r'\\': \\
  • repr(r'\\'): '\\\\'
  • repr(repr(r'\\')): "'\\\\\\\\'"
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

The repr of a string is the literal that it would take to reproduce the string exactly. Since \ is an escape character in literals, you need to double it up to get a single character in the resulting string.

When you type an expression without using print, you get a repr automatically. Thus the \ are doubled up twice, the repr of a repr.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622