目錄
1、習題 8: 列印,列印
學習目標:繼續學習 %r 的格式化輸出。
習題八中的練習程式碼是:
#! -*-coding=utf-8 -*-
formatter = "%r %r %r %r %r "
print formatter % (1, "hello", [1,2,3], (1,2,3), {"name":"jack"})
print formatter % ("one", "two", "three", "four", "five")
print formatter % (True, False, True, False, False)
print formatter % (
"I had this thing. ",
"That you could type up right. ",
"But it didn`t sing. ",
"So I said doognight. ",
"Hello world."
)
上述程式碼的執行結果是:
C:Python27python.exe D:/pythoncode/stupid_way_study/demo8/Exer8-1.py
1 `hello` [1, 2, 3] (1, 2, 3) {`name`: `jack`}
`one` `two` `three` `four` `five`
True False True False False
`I had this thing. ` `That you could type up right. ` "But it didn`t sing. " `So I said doognight. ` `Hello world.`
Process finished with exit code 0
注意:上述程式碼說明兩個點,一個是%r 的作用,是佔位符,可以將後面給的值按原資料型別輸出(不會變),支援數字、字串、列表、元組、字典等所有資料型別。
還有一個需要注意的就是程式碼的最後一行:
print formatter % (
"I had this thing. ",
"That you could type up right. ",
"But it didn`t sing. ",
"So I said doognight. ",
"Hello world."
)
`I had this thing. ` `That you could type up right. ` "But it didn`t sing. " `So I said doognight. ` `Hello world.`
最後輸出的語句中既有單引號,也有雙引號。原因在於 %r 格式化字元後是顯示字元的原始資料。而字串的原始資料包含引號,所以我們看到其他字串被格式化後顯示單引號。 而這條雙引號的字串是因為原始字串中有了單引號,為避免字元意外截斷,python 自動為這段字串新增了雙引號。
2、習題 9: 列印,列印,列印
學習目標:瞭解
的含義
習題九中的練習程式碼是:
#! -*-coding=utf-8 -*-
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan
Feb
Mar
Apr
May
Jun
Jul
Aug"
print "Here are the days: ",days
print "Here are the months: ",months
print """
There`s something going on here.
With the three double-quotes.
We`ll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
C:Python27python.exe D:/pythoncode/stupid_way_study/demo9/Exer9-1.py
Here are the days: Mon Tue Wed Thu Fri Sat Sun
Here are the months: Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
There`s something going on here.
With the three double-quotes.
We`ll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
Process finished with exit code 0
上述程式碼有兩個點需要注意下,一個是換行符
,一個是註釋符三引號。換行符就是避免程式碼過長影響閱讀性而手動進行程式碼換行操作,
其實只是一個字元,類似的還有製表符 ,具體的更過的換行符知識請見下一題。
3、習題 10: 那是什麼?
學習目標:瞭解
的含義,瞭解 的含義
首先來了解一下兩種讓字串擴充套件到多行的方法:
- 換行符
(back-slash n ):兩個字元的作用是在該位置上放入一個“新行(new line)”字元 - 雙反斜槓(double back-slash) :這兩個字元組合會列印出一個反斜槓來
3.1、轉義序列:
下面介紹下再Python中常見的轉義序列:
轉義字元 | 描述 |
---|---|
(在行尾時) | 續行符 |
反斜槓符號 | |
` | 單引號 |
“ | 雙引號 |
a | 響鈴 |
退格(Backspace) | |
e | 轉義 |