[英]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. 您的字符串的反斜杠被用来逃避以下a
字符,所以Python对待\\a
为一个字符。 You can check by printing your string to the console. 您可以通过将字符串打印到控制台进行检查。 It'll print asdasdsdasd
instead of asdasd\\asdasd
. 它会打印asdasdsdasd
而不是asdasd\\asdasd
。 To ensure there is a backslash literal in your string, you must escape the escape character, ie, put 2 backslashes. 为确保字符串中包含反斜杠文字,必须转义转义字符,即放置2个反斜杠。
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
. 你得到的特定错误是分裂的原因返回包含一个元素的列表,它是原始的字符串( ["asdasd\\asdasd"]
所以Python分配"asdasd\\asdasd"
到lhs
,并没有什么分配给rhs
。
lhs, rhs = string.split(r"\a")
r
表示以下字符串是“ raw”,并且反斜杠不应转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.