Python 2.7-需要替换\xampp…“;用另一根绳子

Python 2.7-需要替换\xampp…“;用另一根绳子,python,python-2.7,Python,Python 2.7,Python 2.7。我正在尝试用新字符串替换字符串。代码如下: somestring = "C:\xampp\htdocs\email\BLAHBLAH" thestring = somestring thenewstring = thestring.replace("C:\\xampp\\htdocs\\email\\BLAHBLAH", "something") print thestring print thenewstring 我希望看到打印的内容: C:\xampp\htdocs\

Python 2.7。我正在尝试用新字符串替换字符串。代码如下:

somestring = "C:\xampp\htdocs\email\BLAHBLAH"
thestring = somestring
thenewstring = thestring.replace("C:\\xampp\\htdocs\\email\\BLAHBLAH", "something")
print thestring
print thenewstring
我希望看到打印的内容:

C:\xampp\htdocs\email\BLAHBLAH

something
这就是我得到的错误:

ValueError: invalid \x escape
编辑:让我们假装我没有权限对顶行执行任何操作。它是用石头砌成的。我正在从Word文档中读取元数据,并查找确切的字符串,然后尝试用新字符串替换它。我的代码从第2行开始。这不是该问题的重复,因为我没有使用文字字符串。我已经阅读了这里的许多问题/答案,我理解“\x”是一种特殊的东西,因为我不理解的原因而找不到。我尝试过其中的几个建议(比如使用“repr”或“decode”),但都没有成功


我如何才能让它工作?

如果您在使用

thestring = "C:\xampp\htdocs\email\BLAHBLAH"
您应该使用以下选项:

thestring = r"C:\xampp\htdocs\email\BLAHBLAH"
您想要的最终代码:

thestring = r"C:\xampp\htdocs\email\BLAHBLAH"
thenewstring = thestring.replace("C:\\xampp\\htdocs\\email\\BLAHBLAH", "something")
print thestring
print thenewstring
输出:

C:\xampp\htdocs\email\BLAHBLAH
something
请注意字符串前的“r”。
如果您想了解更多信息:

在第一行添加额外的
'\'
s:
thestring=“C:\\xampp\\htdocs\\email\\BLAHBLAH”
。(它们在第二行中,为什么不在第一行中呢?)。为什么不给新变量分配一个新字符串呢
thenewstring=“something”
可以工作,但不幸的是,在实际代码中,我无法更改“字符串”中的内容。我正在读取Word文档中的元数据,并找到确切的字符串(我无法更改),然后用其他字符串替换它。那么,您的示例的第一行没有赋值?然后请删除它(因为它会导致错误),只需打印字符串的值即可。好吧,我确实有赋值,它只是看起来像这样“contents=file.read().replace(search,replace)”。我只是把它改了,让问题更清楚。file.read()将包含“C:\xampp\htdocs\email\BLAHBLAH”。您调用的函数之一出错。在你发现之前,不要把它们混为一谈。如果在替换任何内容之前打印
fd.read())
的结果,您会看到什么?这非常有效。谢谢@JustaSecUser:如果这是可行的,那么为什么你在评论中告诉DYZ你没有使用字符串文字?是的,你是对的。我迫不及待地说这行得通。它确实适用于我提供的示例,但是如果“C:\xampp\htdocs\email\BLAHBLAH”在一个变量中呢?如何在变量旁边使用“r”?如果要将字符串=[r]file.read()与变量一起使用:print my_variable.encode('string-escape'))