行后续字符后的Python意外字符

时间:2016-07-20 21:22:56

标签: python python-3.x

我是Python的新手。我正在构建一个字符串,它只是一个网络位置的路径,如下所示。但它输出错误:“行后续字符后的Python意外字符”。请帮忙。我看过这篇文章,但我不确定它是否适用于我的场景:

syntaxerror: "unexpected character after line continuation character in python" math

s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name

1 个答案:

答案 0 :(得分:3)

其中一个\反斜杠在其后面的"双引号中转义。字符串的其余部分然后在下一个\反斜杠之前结束,并且第二个反斜杠被视为行继续符。因为在您之后还有另一个",您会收到错误:

s_path_publish_folder = r"\\" + s_host + "\" + s_publish_folder "\" + s_release_name
#                                         ^^ not end of string   ||
#                                        ^--- actual string  ---^||
#                                              line continuation /|
#                                                 extra character /   

你需要加倍那些反斜杠:

s_path_publish_folder = r"\\" + s_host + "\\" + s_publish_folder "\\" + s_release_name

更好的是,在这里使用os.path模块;例如,您可以使用os.path.join()

s_path_publish_folder = r"\\" + os.path.join(s_host, s_publish_folder, s_release_name)

或者您可以使用字符串模板:

s_path_publish_folder = r"\\{}\{}\{}".format(s_host, s_publish_folder, s_release_name)