首页 > 解决方案 > 如何从python中的字符串中删除反斜杠

问题描述

如果我使用替换功能,那么我也会收到错误消息。

filename = input("copy the file path with it's name and extension and paste it here to Encrypt: ")

filename_replace = filename.replace('\ ', " ")

错误说:

Anomalous backslash in string: '\ '. String constant might be missing an r prefix.

标签: python

解决方案


您需要将反斜杠转义为\\.

filename = input("copy the file path with it's name and extension and paste it here to Encrypt: ")
# say it's something like "c:\myfiles\test.txt"
filename_replace = filename.replace("\\"," ")
# becomes "c: myfiles test.txt"

您可以在此处阅读有关转义字符和字符串文字的更多信息: https ://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals


推荐阅读