1

I have a LaTeX file which I want to display in a form field. Input file:

...
\begin{center}
    \vspace{-5mm}
    \noindent
    \textbf{\large Thank You! for Using}
\end{center}
...

I read it in python using readlines()

'\\begin{center}' '\n'

... and so on.

I want the escape characters < no '\n' '\'' '\t' etc> to be removed so that the read contents can be put to a form field. How can it be done?

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
sandish
  • 39
  • 1
  • 6
  • possible duplicate of http://stackoverflow.com/questions/8115261/how-to-remove-all-the-escape-sequences-from-a-list-of-strings – Babu Jan 04 '13 at 06:33

2 Answers2

0

You may use replace function which works on Python strings.

$> a = 'xyz\nbcd'
$> b = a.replace('\n','') # b would be 'xyzbcd'
Nik
  • 5,515
  • 14
  • 49
  • 75
  • I need something to remove all the escapes altogether, simply replace does not work for me. Is there any package, function or like? – sandish Jan 04 '13 at 06:41
  • @sandish Have you checked my comment in the question? – Babu Jan 04 '13 at 06:49
  • yup Babu, I've read it. Thanks, and guys simply using read() instead of readlines() worked for me. – sandish Jan 04 '13 at 07:20
0

I'm not quite sure if you really want to remove all escaped characters of just the trailing \n at the end of each line. This is a common problem many python-programmers have when first reading files, I had it myself a while ago.

readlines() keeps the trailing \n, so that a simple "".join(lines)would restore the original file content.

Just strip the trailing \n from each line.

# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys

lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
    print line
    lines1.append(line)
fh.close()

lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
    line = line.rstrip()
    print line
    lines2.append(line)
fh.close()

The output will be

# -*- coding: utf-8 -*-

"""

Sample for readlines and trailing newline characters

"""

import sys



lines1 = []

fh = open(sys.argv[0],"r")

for line in fh.readlines():

    print line

    lines1.append(line)

fh.close()



lines2 = []

fh = open(sys.argv[0],"r")

for line in fh:

    line = line.rstrip("\n")

    print line

    lines2.append(line)

fh.close()


# -*- coding: utf-8 -*-
"""
Sample for readlines and trailing newline characters
"""
import sys

lines1 = []
fh = open(sys.argv[0],"r")
for line in fh.readlines():
    print line
    lines1.append(line)
fh.close()

lines2 = []
fh = open(sys.argv[0],"r")
for line in fh:
    line = line.rstrip("\n")
    print line
    lines2.append(line)
fh.close()

You could also write line.rstrip("\n") to explicitly only strip the newline characters and not all whitespace characters.

Thorsten Kranz
  • 12,492
  • 2
  • 39
  • 56