- 双引号
spam = "That is Alice's cat."
字符串可以用双引号开始和结束,就像用单引号一样。使用双引号的好处就是字符串中可以使用单引号字符,如以上操作。
- 转义字符
spam = "Say hi to Bob\'s mother" >>> spam "Say hi to Bob's mother"
常见的转义字符:
转义字符 | 打印为 |
\' | 单引号 |
\" | 双引号 |
\t | 制表符 |
\n | 换行符 |
\\ | 反斜杠 |
>>> print("Hello there!\nHow are you?\nI\'m doing fine.") Hello there! How are you? I'm doing fine.
- 原始字符串
>>> print(r"That is Carol\'s cat") That is Carol\'s cat
- 用三重引号的多行字符串
print('''Dear Alice, ... Eve's cat has been arrested for catnapping,cat burglary, and extortion. ... Sincerely, ... Bob''') Dear Alice, Eve's cat has been arrested for catnapping,cat burglary, and extortion. Sincerely, Bob
- 多行注释
井号(#)表示单行注释,但多行字符串常常用多行注释。
"""This is a test Python program. ... Written by A1 Sweigart [email protected] ... This program was designed for python3.0, not python 2.0 ... """
- 字符串下标和切片
>>> spam = "hello world!" >>> spam[0] 'h' >>> spam[1] 'e' >>> spam[-1] '!' >>> spam[0:5] 'hello' >>> spam[6:] 'world!'
- 字符串的in和not in 操作符
>>> "hello" in "hello world" True >>> 'hello' in "Hello" False >>> '' in "spam" True >>> "cats" not in "cats and dogs" False
- 常见的字符串方法