Help me on Backspace please

John Machin sjmachin at lexicon.net
Thu Jun 26 20:06:02 EDT 2008


On Jun 27, 6:32 am, cak... at gmail.com wrote:
> Hi
> I am a beginner on Python and have a problem..
>
> I have text file and reading it line by line and there are backspace
> characters in it like '\b' or anything you want like "#".  I want to
> replace these chars. with Backspace action. I mean deleting the
> previous char. and the \b char also. and writing all cleaned text to a
> file again.
>
> How can I do that.
>

I haven't seen anything like that for ... ummm, a very long time. Used
for bolding and making up your own characters on a daisy-wheel
printer. Where did you get the file from?

If there are no cases of multiple adjacent backspaces (e.g. "blahfoo\b
\b\bblah") you can do:
   new_line = re.sub(r'.\x08', old_line, '')

Note: using \x08 for backspace instead of \b to avoid having to worry
about how many \ to use in the regex :-)

Otherwise you would need to do something like
   while True:
      new_line = re.sub(r'[^\x08]\x08', '', old_line)
      if new_line == old_line: break
      old_line = new_line

And if you were paranoid, you might test for any remaining stray
backspaces, just in case the line contains "illegal" things like
"\bfoo" or "foo\b\b\b\b" etc.

Cheers,
John



More information about the Python-list mailing list