關于Python的兩個實用冷技巧
一. 記得剛開始工作的時候,老大給我們上 C++ 基礎課,告訴我們字符串字面量可以換行(如下代碼),感覺真是如夢如幻。
- #include <stdio.h>
- int main(int argc, char** argv)
- {
- char* w = "hello"
- " "
- "world."
- ;
- printf("%s", w);
- return 0;
- }
輸出:
- hello world.
后來在寫了很久的 Python 以后,才知道 Python 其實也可以的:
- >>> t = ('hello'
- ... ' '
- ... 'world')
- >>> t
- 'hello world'
這個特性很有用,能夠把超長的代碼優(yōu)雅地分為幾行。記得以前在拼 SQL 語言、寫日志條目的時候總為代碼行長度超過 78 感到糾結(見我們的編程規(guī)范:http://blog.csdn.net/lanphaday/article/details/6601123),現在沒有壓力啦。
二. 在寫 absolute32(見:http://blog.csdn.net/lanphaday/article/details/6762023)的測試代碼的時候,為了讓測試代碼兼容 Python2.x/3.x 兩大版本,引入了一砣丑陋的代碼:
- if sys.version < '3':
- exec("chinese = unicode('賴勇浩', 'utf-8')")
- else:
- exec("chinese = '賴勇浩'")
這是因為在 Python2.x 中
- chinese = '賴勇浩'
的編碼不是 unicode 的,而在 Python3.x 中取消了字符串字面量的前綴 u,所以
- chinese = u'賴勇浩'
又直接語法錯誤,當時只好寫下了 exec 的代碼根據不同的版本來進行編譯。后來才知道 Python2.6 中引入了 unicode_literals,可以很方便地寫 2.x/3.x 兼容的代碼:
- >>> x = '中國'
- >>> x
- '\xe4\xb8\xad\xe5\x9b\xbd'
- >>> from __future__ import unicode_literals
- >>> y = '中國'
- >>> y
- u'\u4e2d\u56fd'
這樣,我那砣丑代碼也可以美化掉啦!
原文:http://blog.csdn.net/lanphaday/article/details/6793567
【編輯推薦】