faqts : Computers : Programming : Languages : Python : Snippets : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 4 people (100%) answered Yes
Recently 3 of 3 people (100%) answered Yes

Entry

Handling backspace chars in a string...

Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 110, Tim Peters


"""
Packages: basic_datatypes.strings
"""
"""
> 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
"""