Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove escape character (\) from a list in python?

I want to remove the extra '\' from a list of strings in python.

For example, if my list is this:

cmd = ['a', 'b', '{word}\\\\*', 'd']

it should be this:

cmd = ['a', 'b', '{word}\\\*', 'd']  # I need this exact result

If I iterate through this list while printing each string separately, I am able to get the string "{word}\*".

Meanwhile, when printing this as a whole list, it's showing up as:

['a', 'b', '{word}\\\\*', 'd']

Program:

import re
cmd = ['a', 'b', '{word}\\\\*', 'd']
for i in cmd:
    print("val : ", i)
print("whole list : ", cmd)

Output:

C:\Users\Elcot>python test.py
val :  a
val :  b
val :  {word}\\*
val :  d
whole list :  ['a', 'b', '{word}\\\\*', 'd']

Expected Result:

whole list :  ['a', 'b', '{word}\\*', 'd']
like image 808
Srini Vasan Avatar asked Dec 19 '25 17:12

Srini Vasan


1 Answers

You can convert the string to bytes and then use the bytes.decode method with unicode_escape as the encoding to un-escape a given string:

cmd = [bytes(s, 'utf-8').decode('unicode_escape') for s in cmd]
like image 102
blhsing Avatar answered Dec 21 '25 05:12

blhsing



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!