Handling backspace chars in a string...
Tim Peters
tim_one at email.msn.com
Sun Apr 25 20:45:32 EDT 1999
[Purple]
> I'm in the poistion of having to process strings with arbitrary
> numbers of backspace and newline characters in them.
Your code doesn't appear to care about newlines one way or t'other. Do you
<wink>?
> The backspaces actually get put in the string, so I have to handle
> removing the characters that are backspaced over.
> ... [rather sprawling string + indexing code] ...
> This just looked rather messy to me -- I was curious if anyone know a
> better way?
Assuming "better" means "less messy" here, lists support appending and
deleting quite naturally and efficiently; like
def stripbs(sin):
import string
sout = []
for ch in sin:
if ch == '\b':
del sout[-1:] # a nop if len(sout) == 0
else:
sout.append(ch)
return string.join(sout, '')
This essentially treats the input string as a sequence of opcodes for a
stack machine, where "\b" means "pop" and anything else means "push me!".
don't-use-any-indices-and-you-can't-screw-'em-up<wink>-ly y'rs - tim
More information about the Python-list
mailing list