简体   繁体   English

Python将前进(/)替换为前进(/)

[英]Python replace backward (\) with forward (/)

I am trying to replace \\ with / . 我正在尝试用/替换\\ However, I'm having no success. 但是,我没有成功。 Following is the snapshot of the scenario that I am trying to achieve 以下是我尝试实现的场景的快照

string = "//SQL-SERVER/Lacie/City of X/Linservo\171002"        
print string.replace("\\","/")  

Output: 输出:

//SQL-SERVER/Lacie/City of X/Linservoy002  

Desired output: 所需的输出:

//SQL-SERVER/Lacie/City of X/Linservo/171002

You need to escape "\\" with an extra "\\". 您需要使用额外的“ \\”转义“ \\”。

>>> string = "//SQL-SERVER/Lacie/City of X/Linservo\\171002"
>>> string
'//SQL-SERVER/Lacie/City of X/Linservo\\171002'  
>>> print string.replace("\\","/")
//SQL-SERVER/Lacie/City of X/Linservo/171002
string = r"//SQL-SERVER/Lacie/City of X/Linservo\171002"
print string.replace("\\","/")

output 输出

//SQL-SERVER/Lacie/City of X/Linservo/171002

You have errors both in replace function and in string definition. 您在替换函数和字符串定义中均存在错误。

  • In your string definition \\171 gives char with octal value of 171 – y 在您的字符串定义中, \\171为char提供八进制值171 – y
  • In you replace function, backslash escapes quote. 在替换功能中,反斜杠转义。

You should escape backslashes 您应该转义反斜杠

string = "//SQL-SERVER/Lacie/City of X/Linservo\\171002"
string.replace("\\","/")

You can simply use ".replace" in python or if you want you can use regex : 您可以在python中简单地使用“ .replace”,也可以使用regex:

import re
string = r"//SQL-SERVER/Lacie/City of X/Linservo\171002"

pattern=r'[\\]'

replaced_string=re.sub(pattern,"/",string)

print(replaced_string)

Since your original question shows : "X/Linservo\\171002" here \\171 referring to character encoding so it's replacing \\171 to "y" . 由于您的原始问题显示: "X/Linservo\\171002"这里\\171指的是字符编码,因此它将\\171替换为"y" you can try this in python interpreter : 您可以在python解释器中尝试此操作:

In[2]: print("\171")

y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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