3

My file a contains the text,

bcd\\\\.

With bash, i read the file and print characters from 4th to 8th position as,

tmp=$(cat a)
echo "${tmp:3:4}"

It prints,

\\\\

All happy. Now i use python's array slicing to print characters from 4th to 8th position as,

>>> f = open('a')
>>> v=f.read()
>>> v[3:7]

It prints,

'\\\\\\\\'

Why does bash and python behave differently when there are backslashes?

0

1 Answer 1

4

It is a matter of how python displays strings. Observe:

>>> f = open('a')
>>> v=f.read()
>>> v[3:7]
'\\\\\\\\'
>>> print v[3:7]
\\\\

When displaying v[3:7], the backslashes are escaped. When printing, print v[3:7], they are not escaped.

Other examples

The line in your file should end with a newline character. In that case, observe:

>>> v[-1]
'\n'
>>> print v[-1]


>>> 

The newline character is displayed as a backslash-n. It prints as a newline.

The results for tab are similar:

>>> s='a\tb'
>>> s
'a\tb'
>>> print s
a       b
1
  • 2
    It's the difference between __repr__ and __str__, when you print something out, you get the return from the __str__ function, but when you just have it echoed on the console, you get the __repr__ return value Commented Sep 11, 2015 at 19:32

You must log in to answer this question.