georgewhr
georgewhr

Reputation: 184

How to apply backspace \x08 to a string?

I have a utf-8 list variable lines like this:
[u' ASUS-ASUS-131:66 BF-24-XX-XX-BF--More-- \x08\x08\x08\x08\x08\x08\x08\x08\x08 \x08\x08\x08\x08\x08\x08\x08\x08\x08-A0,'u' ASUS-ASUS-084:R0 AX-24-AX-AC-AX-10]

If I do print lines it will print same as above with backspace \x08 but if I print line by line for i in lines print i

It will print ASUS-ASUS-131:66 BF-24-XX-XX-BF-A0 ASUS-ASUS-084:R0 AX-24-AX-AC-AX-10 I know the print function was actually performing backspace but is there way to assign the print value to a variable to get rid of backspace? I already tried str_var = str(i) but it does not work

Here is a example

>>> test='                                                                                
--More-- \x08\x08\x08\x08\x08\x08\x08\x08\x08         
\x08\x08\x08\x08\x08\x08\x08\x08\x08'
>>> print test

>>> repr(test)
"'                                                                                
--More-- \\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08         
\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08\\x08'"

I don't understand why it shows like this and I want to assign the print output which is empty to a variable

Upvotes: 4

Views: 2926

Answers (2)

Olivier Melançon
Olivier Melançon

Reputation: 22314

Python itself does not treat a backspace specially. You can apply the backspaces by treating your string as a stack where a backspace pops the last character.

Code

def do_backspace(s):
    chars = []
    for c in s:
        if c == '\b' and chars:
            chars.pop()
        else:
            chars.append(c)

    return ''.join(chars)

s = 'Original string: foo\b\b\b'
print(repr(s))

new_s = do_backspace(s)
print(repr(new_s))

Here, extra backspaces are ignored, but you could add a condition to treat them differently.

Output

'Original string: foo\x08\x08\x08'
'Original string: '

Upvotes: 4

Joe Iddon
Joe Iddon

Reputation: 20424

Print repr(some_line). This will show the escape (\x08) chars.

Upvotes: 1

Related Questions