本文章有些內容來源于其他博客主!??!
(1) Python中文亂碼問題的解決
SyntaxError: Non-ASCII character '/xe4' in file test.py on line , but no encoding declared。示例test.py代碼如下:
1 #!/usr/bin/python 2 在終端下執行python test.py指令之后, File "test.py", line 3 SyntaxError: Non-ASCII character '/xe4' in file test.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details這是python編碼的問題, python中默認的編碼格式是ASCII格式, 所以在沒修改編碼格式時無法正確打印漢字。
由于Python源代碼也是一個文本文件,所以,當你的源代碼中包含中文的時候,在保存源代碼時,就需要務必指定保存為UTF-8編碼。當Python解釋器讀取源代碼時,為了讓它按UTF-8編碼讀取,我們通常在文件開頭寫上這兩行:
#!/usr/bin/env python # coding:=utf-8一般輸出的時候采用的格式為
>>>print u'中文‘中文
(2)python的格式化 一個常見的問題是如何輸出格式化的字符串。我們經常會輸出類似’親愛的xxx你好!你xx月的話費是xx,余額是xx’之類的字符串,而xxx的內容都是根據變量變化的,所以,需要一種簡便的格式化字符串的方式。
在Python中,采用的格式化方式和C語言是一致的,用%實現,舉例如下:
>>> 'Hello, %s' % 'world''Hello, world'>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)'Hi, Michael, you have $1000000.'你可能猜到了,%運算符就是用來格式化字符串的。在字符串內部,%s表示用字符串替換,%d表示用整數替換,有幾個%?占位符,后面就跟幾個變量或者值,順序要對應好。如果只有一個%?,括號可以省略。
常見的占位符有:
%d 整數 %f 浮點數 %s 字符串 %x 十六進制整數 其中,格式化整數和浮點數還可以指定是否補0和整數與小數的位數:
>>> '%2d-%02d' % (3, 1)' 3-01'>>> '%.2f' % 3.1415926'3.14'如果你不太確定應該用什么,%s永遠起作用,它會把任何數據類型轉換為字符串:
>>> 'Age: %s. Gender: %s' % (25, True)'Age: 25. Gender: True'對于Unicode字符串,用法完全一樣,但最好確保替換的字符串也是Unicode字符串:
>>> u'Hi, %s' % u'Michael'u'Hi, Michael'有些時候,字符串里面的%是一個普通字符怎么辦?這個時候就需要轉義,用%%來表示一個%:
>>> 'growth rate: %d %%' % 7'growth rate: 7 %'(3)python中的字典的操作方法
dict.clear() 刪除字典中所有元素dict.copy() 返回字典(淺復制)的一個副本dict.fromkeysc(seq,val=None) 創建并返回一個新字典,以seq 中的元素做該字典的鍵,val 做該字典中所有鍵對應的初始值(如果不提供此值,則默認為None)dict.get(key,default=None) 對字典dict 中的鍵key,返回它對應的值value,如果字典中不存在此鍵,則返回default 的值(注意,參數default 的默認值為None)dict.has_key(key) 如果鍵(key)在字典中存在,返回True,否則返回False. 在Python2.2版本引入in 和not in 后,此方法幾乎已廢棄不用了,但仍提供一個 可工作的接口。dict.items() 返回一個包含字典中(鍵, 值)對元組的列表dict.keys() 返回一個包含字典中鍵的列表dict.values() 返回一個包含字典中所有值的列表dict.iter() 方法iteritems(), iterkeys(), itervalues()與它們對應的非迭代方法一樣,不同的是它們返回一個迭代子,而不是一個列表。dict.pop(key[, default]) 和方法get()相似,如果字典中key 鍵存在,刪除并返回dict[key],如果key 鍵不存在,且沒有給出default 的值,引發KeyError 異常。dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 鍵,由dict[key]=default 為它賦值。dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 鍵,由dict[key]=default 為它賦值。(4) Python中argparse模塊的學習 一、簡介: argparse是python用于解析命令行參數和選項的標準模塊,用于代替已經過時的optparse模塊。argparse模塊的作用是用于解析命令行參數,例如python parseTest.py input.txt output.txt --user=name --port=8080。
二、使用步驟:
解釋:首先導入該模塊;然后創建一個解析對象;然后向該對象中添加你要關注的命令行參數和選項,每一個add_argument方法對應一個你要關注的參數或選項;最后調用parse_args()方法進行解析;解析成功之后即可使用,下面簡單說明一下步驟2和3。
方法ArgumentParser(prog=None, usage=None,description=None, epilog=None, parents=[],formatter_class=argparse.HelpFormatter, prefix_chars='-',fromfile_prefix_chars=None, argument_default=None,conflict_handler='error', add_help=True)這些參數都有默認值,當調用parser.print_help()或者運行程序時由于參數不正確(此時python解釋器其實也是調用了pring_help()方法)時,會打印這些描述信息,一般只需要傳遞description參數,如上。
方法add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])其中: name or flags:命令行參數名或者選項,如上面的address或者-p,–port.其中命令行參數如果沒給定,且沒有設置defualt,則出錯。但是如果是選項的話,則設置為None nargs:命令行參數的個數,一般使用通配符表示,其中,’?’表示只用一個,’*’表示0到多個,’+’表示至少一個 default:默認值 type:參數的類型,默認是字符串string類型,還有float、int等類型 help:和ArgumentParser方法中的參數作用相似,出現的場合也一致
最常用的地方就是這些,其他的可以參考官方文檔。下面給出一個例子,基本包括了常見的情形:
import argparsedef parse_args(): description = usage: %prog [options] poetry-fileThis is the Slow Poetry Server, blocking edition.Run it like this: python slowpoetry.py <path-to-poetry-file>If you are in the base directory of the twisted-intro package,you could run it like this: python blocking-server/slowpoetry.py poetry/ecstasy.txtto serve up John Donne's Ecstasy, which I know you want to do. parser = argparse.ArgumentParser(description = description) help = The addresses to connect. parser.add_argument('addresses',nargs = '*',help = help) help = The filename to Operate on.Default is poetry/ecstasy.txt parser.add_argument('filename',help=help) help = The port to listen on. Default to a random available port. parser.add_argument('-p',--port', type=int, help=help) help = The interface to listen on. Default is localhost. parser.add_argument('--iface', help=help, default='localhost') help = The number of seconds between sending bytes. parser.add_argument('--delay', type=float, help=help, default=.7) help = The number of bytes to send at a time. parser.add_argument('--bytes', type=int, help=help, default=10) args = parser.parse_args(); return argsif __name__ == '__main__': args = parse_args() for address in args.addresses: print 'The address is : %s .' % address print 'The filename is : %s .' % args.filename print 'The port is : %d.' % args.port print 'The interface is : %s.' % args.iface print 'The number of seconds between sending bytes : %f'% args.delay print 'The number of bytes to send at a time : %d.' % args.bytes</path-to-poetry-file>運行該腳本:python test.py –port 10000 –delay 1.2 127.0.0.1 172.16.55.67 poetry/ecstasy.txt
輸出為:
The address is : 127.0.0.1 .The address is : 172.16.55.67 .The filename is : poetry/ecstasy.txt .The port is : 10000.The interface is : localhost.The number of seconds between sending bytes : 1.200000The number of bytes to send at a time : 10.(5)Python如何判斷一個字符串為空
#方法一 if oneString: print "not empty" else: print "empty" #方法二 if oneString == "": print "empty" else: print "not empty"總結如下:
len(xxx) == 0xxx == ""if not xxx新聞熱點
疑難解答