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']
I believe you're looking for str.rstrip() which removes the last instance of the character and returns a copy of the resulting string
https://docs.python.org/3.6/library/stdtypes.html#str.rstrip
So looping through your list of strings one-by-one
for i in range(len(cmd)):
cmd[i] = cmd[i].rstrip('\\')
Should remove the last '\\' character from each of your strings in your list of strings.
您可以将字符串转换为字节,然后使用带有unicode_escape
的bytes.decode
方法作为编码来取消转义给定的字符串:
cmd = [bytes(s, 'utf-8').decode('unicode_escape') for s in cmd]
If you really are dealing with an assignment statement, you should know about raw strings in Python. A raw string literal uses the r
prefix like this:
rstr = r"raw string"
regex = r"\(.*\)"
The purpose of raw strings is to reduce the amount of escaping needed when using backslash characters; it is intended for use with other processing engines (like Windows paths, or regular expressions) where the processing engine is going to do its own backslash-handling. There are many fewer escape sequences in raw strings.
Your example of 'word\\\\\\\\*'
would normally be converted to word\\\\*
by the string backslash-escape mechanism. If you want a string with exactly three backslashes, however, you could say r'word\\\\\\*'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.