Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') ('...')or double quotes ("...") with the same result [2]. \ can be used to escape quotes: 除了數字,Python還可以操作字符串,單引號('...')與雙引號(「…」)與相同的結果[ 2 ]。\可以用於轉義引號: 例如:
>>> 'spam eggs' # single quotes 單引號
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote... 用\保留單引號
"doesn't"
>>> "doesn't" # ...or use double quotes instead 用雙引號包圍保留單引號
"doesn't"
>>> '"Yes," he said.' #單引號包圍雙引號保留雙引號
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:在交互解釋器中,輸出字符串用引號括起來,特殊字符用反斜槓進行轉義。雖然這可能有時看起來不同於輸入(封閉引用可以改變),但這兩個字符串是等價的。如果字符串包含單個引號而沒有雙引號,則字符串以雙引號括起來,否則將以單引號括起來。print( )函數通過省略封閉引用和列印轉義字符和特殊字符來生成更可讀的輸出:
>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n means newline 賦值給變量s,這裡\n意味著換行
>>> s # without print(), \n is included in the output 沒有列印,\n被包含在輸出中
>>> print(s) # with print(), \n produces a new line 在列印時s,\n產生新行
First line.
Second line. #在列印時,\n產生新行
If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:如果不希望將字符序列化為特殊字符,則可以在第一次引用之前添加r來使用原始字符串:
>>> print('C:\some\name') # here \n means newline! 此處,\n產生新行
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote 此處前面有r 不產生新行而是隨著輸出
C:\some\name
小結:python操作字符串時,在Python解釋器中單引號與雙引號有相同的作用,用單雙引號擴起來,回車過後第二行輸出上面的內容。\作為轉義字符,用\保留單雙引號,用單引號護雙引號保留輸出雙引號,反之亦然,\n代表換行,如果想是輸出\,則在字符串前面加r 如 print(r'C:\some\name')