python關鍵字、轉義符和字符串格式化

最近在學learn python the hard way,學習到第37章,進行了關於關鍵字、轉義符和字符串格式化的總結。看手頭上的中文版沒有及時更新。因而就把這些翻譯過來,以做查閱。python

關鍵字:express

關鍵字 描述 例子
and 邏輯與
True and False == False
as 做爲with-as語句的一部分
with X as Y: pass
assert 保證某些事情爲真
assert False, "Error!"
break 立刻中止循環
while True: break
class 定義一個類
class Person(object)
continue 中止當前循環,進入下一個循環
while True: continue
def 定義一個函數
def X(): pass
del 從字典中刪除
del X[Y]
elif else if條件判斷
if: X; elif: Y; else: J
else else 條件判斷
if: X; elif: Y; else: J
except 若是發生一個異常,則執行

except ValueError, e:函數

  print e學習

exec 把一個string做爲python來運行
exec 'print "hello"'
finally 無論是否發生異常,都會執行
finally: pass
for 循環遍歷一個集合
for X in Y: pass
from 導入一個模組某個具體的部分
import X from Y
global 聲明你想要一個全局變量
global X
if if條件判斷
if: X; elif: Y; else: J
import 導入一個模組來使用
import os
in for的一部分,也是測試是否在集合裏
for X in Y: pass also 1 in [1] == True
is 判斷相等,與==類似
1 is 1 == True
lambda 建立一個短小的匿名函數
s = lambda y: y ** y; s(3)
not 邏輯非
not True == False
or 邏輯或
True or False == True
pass 這個語句塊是空的
def empty(): pass
print 打印這個字符串
print 'this string'
raise 當發生錯誤時,發起一個異常
raiseValueError("No")
return 退出函數同時返回一個值
def X(): return Y
try 進入這個語句塊,若是發生異常,則進入except
try: pass
while while循環
while X: pass
with
With an expression as a variable do
with X as Y: pass
yeild 在這裏暫停並返回給調用者

def X():測試

   yield Y;this

    X().next()

spa

轉義符 描述
\\ 反斜槓
\' 單引號
\" 雙引號
\a 響鈴
\b 空格
\f 換頁
\n 換行CR+LF
\r CR
\t 製表符
\v 豎向製表
格式 描述 例子
%d 整數
"%d" % 45 == '45'
%i 與%d相同
"%i" % 45 == '45'
%o 八進制
"%o" % 1000 == '1750'
%u 無符號整數
"%u" % -1000 =='-1000'
%x 十六進制小寫
"%u" % -1000 =='-1000'
%X 十六進制大寫
"%X" % 1000 == '3E8'
%e 科學記數法,e小寫
"%e" % 1000 == '1.000000e+03'
%E 科學記數法,E大寫
"%E" % 1000 == '1.000000E+03'
%f 浮點數
"%f" % 10.34 == '10.340000'
%F 與%f相同
"%F" % 10.34 == '10.340000'
%g %f或%e,選擇較短的
"%g" % 10.34 == '10.34'
%G 與%g相同,可是是大寫
"%G" % 10.34 == '10.34'
%c 字符格式
"%c" % 34 == '"'
%r 格式化(用於調試)
"%r" % int == "<type 'int'>"
%s 字符串
"%s there" % 'hi' == 'hi there'
%% 百分數賦值
"%g%%" % 10.34 == '10.34%'
相關文章
相關標籤/搜索