2017-05-31 70 views
0

Python 2.7。我试图用一个新的字符串替换一个字符串。这是代码:Python 2.7 - 需要用另一个字符串替换“ xampp ...”

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”),但我无法让其中任何一项工作。

我该如何得到这个工作?

+1

在第一行添加额外的'''s:'thestring =“C:\\ xampp \\ htdocs \\ email \\ BLAHBLAH”'。 (你有他们在第二行,为什么不在第一?)它也看起来像你用另一个字符串替换_whole_原始字符串。为什么不简单地将一个新的字符串分配给新的变量? 'thenewstring =“something”' – DyZ

+0

这很有效,但不幸的是,在实际的代码中,我无法改变“thestring”里面的内容。我正在阅读Word文档的元数据,并找到确切的字符串(我无法更改),然后用其他字符替换它。 –

+2

因此,你没有_not_实际上在你的例子的第一行有任务?然后请删除它(因为它导致错误),并只需打印'thestring'的值。 – DyZ

回答

-1

如果您在使用

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”。 如果你想了解更多关于这个的信息:What exactly do "u" and "r" string flags do in Python, and what are raw string literals?

+0

这工作完美。谢谢! –

+1

@JustaSecUser:如果这有效,那么为什么你在评论中告诉DYZ你没有使用字符串文字? –

+0

是的,你说得对。我跳过枪说这个工程。它*确实*适用于我提供的示例,但如果“C:\ xampp \ htdocs \ email \ BLAHBLAH”出现在变量中呢?我将如何使用变量旁边的“r”? thestring = [r] file.read() –

相关问题