当前位置:编程学习 > 网站相关 >>

两个Python的冷技巧


记得刚开始工作的时候,老大给我们上 C++ 基础课,告诉我们字符串字面量可以换行(如下代码),感觉真是如梦如幻。

view plaincopy to clipboardprint?#include <stdio.h>  
 
int main(int argc, char** argv) 

        char* w = "hello" 
                " " 
                "world." 
                ; 
        printf("%s", w); 
        return 0; 

#include <stdio.h>

int main(int argc, char** argv)
{
        char* w = "hello"
                " "
                "world."
                ;
        printf("%s", w);
        return 0;
}
输出:

view plaincopy to clipboardprint?hello world. 
hello world.后来在写了很久的 Python 以后,才知道 Python 其实也可以的:

view plaincopy to clipboardprint?>>> t = ('hello' 
... ' ' 
... 'world') 
>>> t 
'hello world' 
>>> t = ('hello'
... ' '
... 'world')
>>> t
'hello world'这个特性很有用,能够把超长的代码优雅地分为几行。记得以前在拼 SQL 语言、写日志条目的时候总为代码行长度超过 78 感到纠结(见我们的编程规范:http://blog.csdn.net/lanphaday/article/details/6601123),现在没有压力啦。


在写 absolute32(见:http://blog.csdn.net/lanphaday/article/details/6762023)的测试代码的时候,为了让测试代码兼容 Python2.x/3.x 两大版本,引入了一砣丑陋的代码:

view plaincopy to clipboardprint?if sys.version < '3': 
        exec("chinese = unicode('赖勇浩', 'utf-8')") 
else: 
        exec("chinese = '赖勇浩'") 
if sys.version < '3':
        exec("chinese = unicode('赖勇浩', 'utf-8')")
else:
        exec("chinese = '赖勇浩'")这是因为在 Python2.x 中 view plaincopy to clipboardprint?chinese = '赖勇浩' 
chinese = '赖勇浩'的编码不是 unicode 的,而在 Python3.x 中取消了字符串字面量的前缀 u,所以view plaincopy to clipboardprint?chinese = u'赖勇浩' 
chinese = u'赖勇浩'又直接语法错误,当时只好写下了 exec 的代码根据不同的版本来进行编译。后来才知道 Python2.6 中引入了 unicode_literals,可以很方便地写 2.x/3.x 兼容的代码:

view plaincopy to clipboardprint?>>> x = '中国' 
>>> x 
'\xe4\xb8\xad\xe5\x9b\xbd' 
>>> from __future__ import unicode_literals 
>>> y = '中国'  
>>> y 
u'\u4e2d\u56fd' 
>>> x = '中国'
>>> x
'\xe4\xb8\xad\xe5\x9b\xbd'
>>> from __future__ import unicode_literals
>>> y = '中国'
>>> y
u'\u4e2d\u56fd'这样,我那砣丑代码也可以美化掉啦!


 作者“赖勇浩的编程私伙局”

补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,