Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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
share|improve this answer
1  
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 at 19:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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