-4

Suppose my txt file data.txt has the following content:

'\\|'
'//'

And I want to read the data.txt:

In [1]: with open('data.txt') as f:
   ...:     data = f.readlines()
   ...:     

In [2]: data
Out[2]: ["'\\\\|'\n", "'//'\n"]

In [3]: data[0]
Out[3]: "'\\\\|'\n"

And I want to

In [4]: ' '.join(data)
Out[4]: "'\\\\|' '//'"

But Python double read the \. And the expected output is:

In [2]: data
Out[2]: ["'\\|'\n", "'//'\n"]

How can I get the expected output in a more efficient and pythonic way?

GoingMyWay
  • 16,802
  • 32
  • 96
  • 149
  • 1
    Check this [Python - Backslash Quoting in String Literals](http://stackoverflow.com/questions/301068/python-backslash-quoting-in-string-literals) – Ani Menon Sep 05 '16 at 08:00
  • If you use an output that is meant and used for debugging purposes you will get that. Use `print` if you want to print a string. – Matthias Sep 05 '16 at 08:25

1 Answers1

3

It did not "double read" the \, it simply escaped it. The string itself is '\\|'\n, it is just represented as '\\\\|'\n.

for string in data:
    print(string)

>> '\\|'

   '//'

The blank line is the first line in the file has a trailing \n. You may want to get rid of that with strip:

with open('data.txt') as f:
    data = [line.strip() for line in f]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
DeepSpace
  • 78,697
  • 11
  • 109
  • 154