Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2793302
  • 博文数量: 471
  • 博客积分: 7081
  • 博客等级: 少将
  • 技术积分: 5369
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-04 21:55
文章分类

全部博文(471)

文章存档

2014年(90)

2013年(69)

2012年(312)

分类: LINUX

2013-02-26 16:39:04

特殊符号

 

和C/C++,Java等语言相比,有些符号在Python中有特殊定义,在这里列一下。

 

_ : 最后一个表达式的值

 

例子:

 

 


  1. >>> 4/2  
  2. 2  
  3. >>> _  
  4. 2  
  5. >>> print _ + 10  
  6. 12  
>>> 4/2 2 >>> _ 2 >>> print _ + 10 12 


 

% : 字符串格式操作符

 

例子:

 


  1. >>> print '%s is number %d!' % ('Python'1)  
  2. Python is number 1!  
>>> print '%s is number %d!' % ('Python', 1) Python is number 1! 


 

>> : 输出重定向

 

例子:


  1. >>> logfile = open('/tmp/mylog.txt','a')  
  2. >>> print >> logfile, 'Fatal error:invalid input!'  
  3. >>> logfile.close()  
>>> logfile = open('/tmp/mylog.txt','a') >>> print >> logfile, 'Fatal error:invalid input!' >>> logfile.close()


 

 

# : 注释符号,从#符号开始直到行末,都是注释内容

 

// : 对于Python 3+,'/'表示真正的除法,'//'表示floor除法(对于2.x版本,需要导入__future__ division才会这样)

 


  1. # Python version 2.5   
  2. >>> 5/2  
  3. 2  
  4. >>> 5//2  
  5. 2  
  6. >>> from __future__ import division   
  7. >>> 5/2  
  8. 2.5  
  9. >>> 5//2  
  10. 2  
# Python version 2.5 >>> 5/2 2 >>> 5//2 2 >>> from __future__ import division >>> 5/2 2.5 >>> 5//2 2


 

+, * : 对于字符串,'+'表示字符串连接,'*'表示字符串重复

 

例子:


  1. >>> 'hello' + ' world!'  
  2. 'hello world!'  
  3. >>> 'hello' * 2  
  4. 'hellohello'  
>>> 'hello' + ' world!' 'hello world!' >>> 'hello' * 2 'hellohello'


 

[begin:end] : 切片操作符号,取值范围为: [begin, end),如果不填begin,则表示end之前(不包括end本身)所有元素;不填end,则表示begin及其后所有元素。索引从0开始,特别的,最后的索引可以用-1表示

 

例子:


  1. >>> val = [1,2,3,4]  
  2. >>> val[0]     
  3. 1  
  4. >>> val[-1]  
  5. 4  
  6. >>> val[0:-1]  
  7. [123]  
  8. >>> val[0:]   
  9. [1234]  
  10. >>> val[:-1]  
  11. [123]  
  12. >>> val[:]  
  13. [1234]  
>>> val = [1,2,3,4] >>> val[0] 1 >>> val[-1] 4 >>> val[0:-1] [1, 2, 3] >>> val[0:] [1, 2, 3, 4] >>> val[:-1] [1, 2, 3] >>> val[:] [1, 2, 3, 4]


 

''' : 连续的3个引号,作为字符串的开头和结尾,允许字符串跨多行,并且可以包含换行符制表符等特殊符号。需要一段HTML或者SQL语句时,使用'''会使代码更简洁明了

 


  1. cursor.execute(''''' 
  2.     insert into warning_type 
  3.     (type_id,type_name,urgency,description) 
  4.     values(0,'测试信息',0,'测试信息'); 
  5. ''')  
cursor.execute(''' insert into warning_type (type_id,type_name,urgency,description) values(0,'测试信息',0,'测试信息'); ''')


 

u : 字符串前加u符号,表示此字符串是一个unicode的字符串

 


  1. >>> s = 'hello'  
  2. >>> type(s)  
  3. 'str'>  
  4. >>> s = u'hello'  
  5. >>> type(s)  
  6. 'unicode'>  
>>> s = 'hello' >>> type(s) >>> s = u'hello' >>> type(s)


阅读(6104) | 评论(0) | 转发(1) |
0

上一篇:python 基本类型

下一篇:控制结构--if

给主人留下些什么吧!~~