简体   繁体   中英

Unable to split a string with a back slash despite using escape character

I'm getting an error when I try to split a string like this:

string = "asdasd\asdasd"
lhs, rhs = string.split("\\")
print(rhs)

I receive the following error when I try to print the right hand side string.

Traceback (most recent call last):
  File "C:/Users/Michael/PycharmProjects/untitled/expiriment2.py", line 2, in <module>
    lhs, rhs = string.split("\\")
ValueError: need more than 1 value to unpack

I'm not sure what you're trying to achieve, but you could try using raw strings like the following:

string = r"asdasd\asdasd"
lhs, rhs = string.split("\\")
print rhs

Your string's backslash is being used to escape the following a character, so python treats \\a as one character. You can check by printing your string to the console. It'll print asdasdsdasd instead of asdasd\\asdasd . To ensure there is a backslash literal in your string, you must escape the escape character, ie, put 2 backslashes.

string = "asdasd\\\\asdasd" lsh, rhs = string.split("\\\\")

The reason you're getting that specific error is that split returns a list containing one element that is the original string ( ["asdasd\\asdasd"] ), so python is assigning "asdasd\\asdasd" to lhs , and there is nothing to assign to rhs .

lhs, rhs = string.split(r"\a")

r表示以下字符串是“ raw”,并且反斜杠不应转义。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM