Python 中使用反斜杠转义引号和其它特殊字符来准确地表示。
如果字符串包含有单引号但不含双引号,则字符串会用双引号括起来,否则用单引号括起来。对于这样的输入字符串,print() 函数会产生更易读的输出。
跨行的字面字符串可用以下几种方法表示。使用续行符,即在每行最后一个字符后使用反斜线来说明下一行是上一行逻辑上的延续:网易云课堂Python编程量化AI全栈零基础入门
以下使用 \n 来添加新行:
‘“Isn’t,” she said.’ ‘“Isn’t,” she said.’ >>> print(’“Isn’t,” she said.’) “Isn’t,” she said. >>> s = ‘First line.\nSecond line.’ # \n 意味着新行 >>> s # 不使用 print(), \n 包含在输出中 ‘First line.\nSecond line.’ >>> print(s) # 使用 print(), \n 输出一个新行 First line. Second line.
以下使用 反斜线(\) 来续行:
hello = “This is a rather long string containing\n\ several lines of text just as you would do in C.\n\ Note that whitespace at the beginning of the line is\ significant.