Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 501
georgewhr Avatar asked Oct 27 '25 21:10

georgewhr


2 Answers

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: '
like image 137
Olivier Melançon Avatar answered Oct 29 '25 12:10

Olivier Melançon


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

like image 38
Joe Iddon Avatar answered Oct 29 '25 11:10

Joe Iddon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!