EbinPaulose
EbinPaulose

Reputation: 1139

How read \t in python?

I have a text file like this

i am a messi fan \t

I am using this code to read

 f = open(input_para['controle_file'], 'r')
        filedata = f.read().splitlines()

now my output is

i am a messi fan \\t

required output is i am a messi fan \t

How can I get this exact data from the text file in python?

Upvotes: 3

Views: 2142

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251106

What you're seeing is a repr version of the string, you'll not get any '\\t' when you use str or print that string.

>>> strs = "i am a messi fan \t"
>>> repr(strs)
"'i am a messi fan \\t'"

>>> str(strs)
'i am a messi fan \t'
>>> print strs
i am a messi fan    

Upvotes: 1

mgilson
mgilson

Reputation: 310089

The difference is based on how python represents a string. If you print it, you should see what you want.

>>> r"foo\t"
'foo\\t'
>>> print r"foo\t"
foo\t

This boils down to the difference between repr and str ...

>>> s = r"foo\t"
>>> print str(s)
foo\t
>>> print repr(s)
'foo\\t'

And the reasoning is that if possible, repr should return a string suitable for recreating the object. In your case, if repr didn't add an extra escaping backslash, then the string representation would look like it had a tab character in it.

Upvotes: 6

Related Questions