Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Triple Quotes (Ba dấu ngoặc kép) trong Python

Triple quotes của Python giúp chuỗi trải dài nhiều dòng, bao gồm verbatim NEWLINE, TAB, và ký tự đặc biệt khác.

Cú pháp triple quotes gồm ba dấu single hoặc double quotes liên tiếp.

Ví dụ

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

Kết quả

Khi mã chạy, kết quả sau. Chú ý mọi ký tự đặc biệt được chuyển sang dạng in, xuống đến NEWLINE cuối cùng giữa "up." và closing triple quotes. NEWLINE xảy ra do carriage return rõ ràng hoặc 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 string không coi backslash là ký tự đặc biệt. Mọi ký tự bạn đưa vào raw string giữ nguyên như bạn viết:

Ví dụ

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

Kết quả

C:\nowhere

Bây giờ dùng raw string. Đặt biểu thức trong r'expression':

Ví dụ

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

Kết quả

C:\\nowhere