比较“细”的定义指路:转义字符_百度百科转义字符(Escape character),所有的ASCII码都可以用“\”加数字(一般是8进制数字)来表示。而C中定义了一些字母前加"\"来表示常见的那些不能显示的ASCII字符,如\0,\t,\n等,就称为转义字符,因为后面的字符,都不是它本来的ASCII字符意思了。https://baike.baidu.com/item/%E8%BD%AC%E4%B9%89%E5%AD%97%E7%AC%A6/86397通俗的讲,转义字符就是:反斜杠 + 想要实现的转义功能首字母
(1)字符串中含有反斜杠、单引号、双引号等特殊字符时
- print('转义字符中的\'转义\'是什么意思')
-
- >> 转义字符中的'转义'是什么意思
- print('他说:\"Hello Python\"')
-
- >> 他说:"Hello Python"
- print('C:\\Users')
-
- >> C:\Users
(2)字符串中含有换行、水平制表符、回车等无法直接表达的特殊字符时
- print('hello\nworld')
-
- >> hello
- >> world
- print('hello\tworld')
- print('helloooo\tworld')
-
- >> hello world
- >> helloooo world
注意:'\t'所占空格数与字符串所占的制表位剩余位置有关
- print('hello\bworld')
-
- >> hellworld
光标回到当前行的行首,如果接着输出的话,本行以前的内容会被逐一覆盖
- print('hello\rworld')
-
- >> world
当我们不希望字符串中的转义字符发挥其原本的作用而是同其他字符一起被打印出时,我们只需在字符串前加上 'r' 或 'R'
- print(r'hello\nworld')
- print(R'hello\nworld')
-
- >> hello\nworld
- >> hello\nworld
字符串不能以 '\'为结尾
print('hello world\') # 错误示范