在python中的字符串之前'r'代表什么? [英] What does an 'r' represent before a string in python?

查看:56
本文介绍了在python中的字符串之前'r'代表什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解为什么我们在python中的路径名之前使用r,例如

I want to understand why do we use a r before a path name in python such as

dirname = r'C:\temp\parts'

推荐答案

r 表示字符串将被视为原始字符串.

r means the string will be treated as raw string.

来自这里:

当存在 'r' 或 'R' 前缀时,a 后面的字符反斜杠包含在字符串中而没有更改,并且所有反斜杠留在字符串中.例如,字符串文字r"\n" 由两个字符组成:一个反斜杠和一个小写的 'n'.字符串引号可以用反斜杠转义,但反斜杠留在字符串中;例如, r"\"" 是有效的字符串文字由两个字符组成:一个反斜杠和一个双引号;r"\" 是不是有效的字符串文字(即使是原始字符串也不能以奇数结尾反斜杠的数量).具体来说,原始字符串不能以单个反斜杠(因为反斜杠会转义以下引号特点).另请注意,单个反斜杠后跟换行符是解释为这两个字符作为字符串的一部分,而不是作为续行.

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

这篇关于在python中的字符串之前'r'代表什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆