在python中将单斜线替换为双斜线

jgovgodb  于 2023-02-06  发布在  Python
关注(0)|答案(2)|浏览(520)

想把下面的路径从单斜线转换成双斜线,但是当我打印文件时,它在python中删除了\b和\U作为它的特殊字符。对于\U,它给出了unicode错误。

file = "C:\Users\Dell\Desktop\ProjectShadow\button\button.py"

预期产出:

file = "C:\\Users\\Dell\\Desktop\\ProjectShadow\\button\\button.py"

j91ykkif

j91ykkif1#

对原始字符串使用r,并使用str.replace方法将所有单斜线替换为双斜线。

file = r"C:\Users\Dell\Desktop\ProjectShadow\button\button.py"
file = file.replace("\\", "\\\\")
C:\\Users\\Dell\\Desktop\\ProjectShadow\\button\\button.py
nhjlsmyf

nhjlsmyf2#

path = "C:\U0005\b000"

# replace single slash with double slash
double_slash_path = path.replace("\\", "\\\\")

# escape special characters
double_slash_path = double_slash_path.replace("\b", "\\b")
double_slash_path = double_slash_path.replace("\U", "\\U")

print(double_slash_path)

相关问题