Triple quotes ของ Python ช่วยให้ strings ครอบหลายบรรทัดได้ รวมถึง NEWLINEs, TABs และตัวอักษรพิเศษอื่นๆ แบบ verbatim
ไวยากรณ์ของ triple quotes ประกอบด้วยสาม single หรือ double quotes ติดต่อกัน
ตัวอย่าง
#!/usr/bin/python
para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """
print para_str
ผลลัพธ์ (Output)
เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้
สังเกตว่าทุกตัวอักษรพิเศษถูกแปลงเป็นรูปแบบพิมพ์แล้ว จนถึง NEWLINE สุดท้ายที่ท้ายสตริงระหว่าง "up." และ closing triple quotes สังเกตด้วยว่า NEWLINEs เกิดขึ้นได้ทั้ง explicit carriage return ที่ท้ายบรรทัดหรือ escape code (\n):
this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up.
Raw strings ไม่จัดการ backslash เป็นตัวอักษรพิเศษเลย ทุกตัวอักษรที่คุณใส่ใน raw string จะคงที่เหมือนที่คุณเขียน:
ตัวอย่าง
#!/usr/bin/python
print 'C:\\nowhere'
ผลลัพธ์ (Output)
เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:
C:\nowhere
ตอนนี้ลองใช้ raw string เราจะวาง expression ใน r'expression' ดังนี้:
ตัวอย่าง
#!/usr/bin/python
print r'C:\\nowhere'
ผลลัพธ์ (Output)
เมื่อรันโค้ดข้างต้น จะได้ผลลัพธ์ดังนี้:
C:\\nowhere