【PYTHON】Python的String。Python escape Characters.- Python的跳脫字元
跳脫字元
使用跳脫字元的情境在,當需要在字串內插入一個非法的字元來顯示。
使用反斜線 \ 為跳脫字元之後跟隨著需要插入的字元。
在字串裡面在夾雜2個雙引號間如果再使用雙引號是個錯誤的範例,如下所示:
範例:
你將會出現錯誤訊息,如果你使用雙引號在其中間又加入雙引號:
txt = "We are the so-called "Vikings" from the north."上面輸出錯誤訊息: File "<stdin>", line 1 txt = "We are the so-called "Vikings" from the north." ^SyntaxError: invalid syntax
為解決這個問題, 我們試用跳脫字元 \":
範例:
當使用跳脫字元就可用雙引號,正常在引號內不可以在有裡面的雙引號,如同不可巢狀雙引號。
txt = "We are the so-called \"Vikings\" from the north.print(txt)上面輸出:We are the so-called "Vikings" from the north.跳脫字元表
其他在Python中使用的跳脫字元表:
| Code | Result | Try it |
|---|---|---|
| \' | Single Quote | |
| \\ | Backslash | |
| \n | New Line | |
| \r | Carriage Return | |
| \t | Tab | |
| \b | Backspace | |
| \f | Form Feed | |
| \ooo | Octal value | |
| \xhh | Hex value |

留言
張貼留言