未知的python表达式filename=r'/path/to/file'

2024-03-29 06:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现这个可能非常有用的pythonscript,但是遇到了这些我以前从未见过的表达式:

inputfilename = r'/path/to/infile'
outputfilename = r'/path/to/outfile'

我找不到办法去寻找它。r'...'做什么?

谢谢你的帮助!


Tags: topath表达式infileoutfilepythonscript办法inputfilename
3条回答

它被称为原始字符串文字。

根据^{}

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. 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.

...

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C

在Python中,它只意味着原始字符串。意思是字符串中的任何内容都是字符串。例如,如果要添加斜杠:

string1 = "happy\/cheese"

您需要在斜杠前面添加\,因为斜杠是转义字符。例如,\n表示新行。

如果保持字符串原始,它将确保字符串中的内容不会以特殊方式解释。例如,如果您编写了string2 = r"\n",它只会在字符串时给您"\n",而不是一个新行。

您可以从here了解更多关于它们的信息。

现在,这在您的例子中完成了,因为文件路径有很多斜杠,我们希望避免使用这么多的反斜杠。

r'..'字符串修饰符使'..'字符串被逐字解释为。这意味着,r'My\Path\Without\Escaping'将计算为'My\Path\Without\Escaping'-而不会导致反斜杠转义字符。previor相当于'My\\Path\\Without\\Escaping'字符串,但没有raw修饰符。

注意:字符串不能以奇数个反斜杠结尾,即r'Bad\String\Example\'不是正确的字符串。

相关问题 更多 >