Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
EbinPaulose Avatar asked Aug 03 '26 12:08

EbinPaulose


1 Answers

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.

like image 169
mgilson Avatar answered Aug 06 '26 02:08

mgilson