My file a contains the text,


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?


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]
>>> 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
>>> print s
a       b
  • 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 – Jacob Minshall Sep 11 '15 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.