Skip to main content
 首页 » 编程设计

Python 将特殊字符添加到路径字符串

2025年05月04日43虾米哥

我正在尝试使用 Python 2.7 中的路径

这就是我在主课中尝试做的事情:

program = MyProgram() 
program.doSomething('C:\Eclipse\workspace\MyProgram\files\12345678_Testing1_ABCD005_Static_2214_File12.txt') 

在函数 doSomething(filePath) 中,字符串看起来像这样:

所以有一种特殊字符加上一些字符被完全删除。是什么导致了这个问题?

请您参考如下方法:

\ 是 Python 中的转义字符。 According to docs ,您已经创建了带有 \f ASCII Formfeed (FF) 字符的字符串。

String literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

使用双斜杠(\\ - 转义转义字符)或使用原始字符串文字(r"some\path")。

String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.