在 Python 中想要在字串中插入 特殊符號或非法字符(像是雙引號、換行等),就需要使用 Escape Character(跳脫字元)。這可以讓 Python 正確地理解字串內容,而不會誤會語法錯誤。
雙引號 \"
用於字串中包含雙引號時
sentence = "He said, \"Python is awesome!\""output :
print(sentence)
He said, "Python is awesome!"
單引號 \'
在單引號內部使用單引號
sentence = 'It\'s a beautiful day.'
print(sentence)
output :
It's a beautiful day.
反斜線 \\
輸出一個反斜線
path = "C:\\Users\\Debby\\Documents"
print(path)
output :
C:\Users\Debby\Documents
換行 \n
在字串中換行
message = "Hello,\nWorld!"
print(message)
output :
Hello,
World!
Tab 縮排 \t
模擬表格效果
print("Name\tAge\tCity")
print("Debby\t99\tTainan")
output :
Name Age City
Ben 99 Tainan
Backspace \b
退格,刪除前一個字元
text = "Helloo\b!"
print(text)
output :
Hello!