python转义序列_Python中的转义序列

python转义序列

Escape sequences allow you to include special characters in strings. To do this, simply add a backslash (\) before the character you want to escape.

转义序列允许您在字符串中包括特殊字符。 为此,只需在要转义的字符之前添加反斜杠( \ )。

For example, imagine you initialized a string with single quotes:

例如,假设您使用单引号初始化了一个字符串:

s = 'Hey, whats up?'
print(s)

Output:

输出:

Hey, whats up?

But if you include an apostrophe without escaping it, then you will get an error:

但是,如果您在没有转义的情况下加入了撇号,则会出现错误:

s = 'Hey, what's up?'
print(s)

Output:

输出:

File "main.py", line 1
    s = 'Hey, what's up?'
                   ^
SyntaxError: invalid syntax

To fix this, just escape the apostrophe:

要解决此问题,只需跳过撇号:

s = 'Hey, what\'s up?'
print(s)

To add newlines to your string, use \n:

要在字符串中添加换行符,请使用\n

print("Multiline strings\ncan be created\nusing escape sequences.")

Output:

输出:

Multiline strings
can be created
using escape sequences.

An important thing to remember is that, if you want to include a backslash character in a string, you will need to escape that. For example, if you want to print a directory path in Windows, you'll need to escape each backslash in the string:

要记住的重要一点是,如果要在字符串中包含反斜杠字符,则需要对此进行转义。 例如,如果要在Windows中打印目录路径,则需要对字符串中的每个反斜杠进行转义:

print("C:\\Users\\Pat\\Desktop")

Output:

输出:

C:\Users\Pat\Desktop

原始字符串 (Raw strings)

A raw string can be used by prefixing the string with r or R, which allows for backslashes to be included without the need to escape them. For example:

可以通过在字符串前面加上rR来使用原始字符串,从而可以包含反斜杠而无需对其进行转义。 例如:

print(r"Backslashes \ don't need to be escaped in raw strings.")

Output:

输出:

Backslashes \ don't need to be escaped in raw strings.

But keep in mind that unescaped backslashes at the end of a raw string will cause and error:

但是请记住,在原始字符串末尾使用未转义的反斜杠会引起错误:

print(r"There's an unescaped backslash at the end of this string\")

Output:

输出:

File "main.py", line 1
    print(r"There's an unescaped backslash at the end of this string\")
                                                                      ^
SyntaxError: EOL while scanning string literal

常见的转义序列 (Common escape sequences)

Escape SequenceMeaning
\Backslash (\)
'Single quote (')
"Double quote (")
\nASCII Linefeed (adds newline)
\bASCII Backspace
转义序列 含义
\ 反斜杠( \ )
' 单引号( ' )
双引号( " )
\ n ASCII换行符(添加换行符)
\ b ASCII退格键

A full list of escape sequences can be found here in the Python docs.

转义序列的完整列表,可以发现这里的Python文档。

翻译自: https://www.freecodecamp.org/news/escape-sequences-python/

python转义序列

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值