String Literals

By and large, strings are fairly easy to use in Python. Perhaps the most complicated thing about them is that there are so many ways to write them in your code:

 

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

 
  • Single quotes: 'spa"m'
  • Double quotes: "spa'm"
  • Triple quotes: '''... spam ...''', """... spam ..."""
  • Escape sequences: "s\tp\na\0m"
  • Raw strings: r"C:\new\test.spm"
  • Byte strings in 3.0 (see Chapter 36): b'sp\x01am'
  • Unicode strings in 2.6 only (see Chapter 36): u'eggs\u0020spam'

The single- and double-quoted forms are by far the most common; the others serve specialized roles, and we’re postponing discussion of the last two advanced forms until Chapter 36. Let’s take a quick look at all the other options in turn.