Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คำคมสามคำใน Python


เครื่องหมายอัญประกาศสามอันของ Python ช่วยได้ด้วยการอนุญาตให้สตริงขยายหลายบรรทัด รวมถึง NEWLINE แบบคำต่อคำ TAB และอักขระพิเศษอื่นๆ

ไวยากรณ์สำหรับเครื่องหมายคำพูดสามตัวประกอบด้วยเครื่องหมายคำพูดเดี่ยวหรือคู่ติดต่อกันสามคำ

ตัวอย่าง

#!/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

ผลลัพธ์

เมื่อโค้ดด้านบนถูกรัน มันจะให้ผลลัพธ์ดังต่อไปนี้

สังเกตว่าอักขระพิเศษทุกตัวถูกแปลงเป็นรูปแบบที่พิมพ์แล้ว ลงไปที่ NEWLINE สุดท้ายที่ท้ายสตริงระหว่าง "ขึ้น" และปิดอัญประกาศสามเท่า โปรดทราบด้วยว่า NEWLINE เกิดขึ้นได้ด้วยการขึ้นบรรทัดใหม่อย่างชัดแจ้งที่ท้ายบรรทัดหรือ 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.

สตริงดิบไม่ถือว่าแบ็กสแลชเป็นอักขระพิเศษเลย อักขระทุกตัวที่คุณใส่ลงในสตริงดิบจะยังคงเหมือนเดิม -

ตัวอย่าง

#!/usr/bin/python
print 'C:\\nowhere'

ผลลัพธ์

เมื่อโค้ดด้านบนถูกรัน มันจะให้ผลลัพธ์ดังต่อไปนี้ −

C:\nowhere

ตอนนี้เรามาใช้ประโยชน์จากสตริงดิบกัน เราจะใส่นิพจน์ใน r'expression' ดังนี้ −

ตัวอย่าง

#!/usr/bin/python
print r'C:\\nowhere'

ผลลัพธ์

เมื่อโค้ดด้านบนถูกรัน มันจะให้ผลลัพธ์ดังต่อไปนี้ −

C:\\nowhere