简体   繁体   English

如何删除 python 字符串中的所有“\”并将它们替换为“/”?

[英]How can i remove all the "\" in a python string and replace them with "/"?

I wrote a python script that uses an image from the current folder which is in it and i turned it to .exe file so i can run it without clicking on the .py file, but if i want to give it to my friends the cwd (current working directory) will not be the same so the string which represents mine won't work there so i did this:我写了一个 python 脚本,它使用当前文件夹中的图像,我把它变成了.exe文件,这样我就可以运行它而不用点击.py文件,但是如果我想把它给我的朋友cwd (当前工作目录)将不一样,所以代表我的字符串在那里不起作用,所以我这样做了: 在此处输入图像描述

you can't use \ in python because it's a special character in strings and in my script where i try to replace it with / , it doesn't work and all the script in that area becomes green as you can see and i don't know what to do.你不能在 python 中使用\ ,因为它是字符串中的特殊字符,在我尝试用/替换它的脚本中,它不起作用,并且该区域中的所有脚本都变成绿色,如你所见,我不不知道该怎么办。

The solution is simple.解决方法很简单。 Don't do r'\' but rather \\ .不要做r'\'而是\\ Here's an example:这是一个例子:

s= r'bruh\bruh\bruh' # this
s = 'bruh\\bruh\\bruh' # or this both work
print(s.replace('\\','/'))

As people mentioned you can try with \\ .正如人们提到的,您可以尝试使用\\ for some reasons it deson't work you can also try.由于某些原因它不起作用,您也可以尝试。

import os
strs = "somestring\ok"
strs = strs.replace(os.sep,'/')
print(strs)

Gives #给#

somestring/ok

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

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