Chinaunix首页 | 论坛 | 博客
  • 博客访问: 90063
  • 博文数量: 30
  • 博客积分: 1501
  • 博客等级: 上尉
  • 技术积分: 300
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-01 09:23
文章分类

全部博文(30)

文章存档

2011年(6)

2010年(24)

分类: Python/Ruby

2010-11-05 16:14:44

合法标识符
1.不能以数字开头
>>> 2bin=2
  File "", line 1
    2bin=2
       ^
SyntaxError: invalid syntax
2.不能包含非法字符
>>> ssd@f=1
  File "", line 1
    ssd@f=1
       ^
SyntaxError: invalid syntax
3.数字不能作为标识符
>>> 123='wdsa'
SyntaxError: can't assign to literal
4.不能包含空格
>>> fds fds=1
  File "", line 1
    fds fds=1
          ^
SyntaxError: invalid syntax
5.不能包含运算符
>>> sdf+sdf=1
SyntaxError: can't assign to operator
6.python保留关键字不能作为标识符
单双引号字符串
字符串里有'时:
>>> 'it's a dog'
  File "", line 1
    'it's a dog'
        ^
SyntaxError: invalid syntax
解决方案如下
>>> "it's a dog"
"it's a dog"
>>> 'it\'s a dog'
"it's a dog"
字符串里有"时:
>>> "it is a "dog""
  File "", line 1
    "it is a "dog""
                ^
SyntaxError: invalid syntax
解决方案如下
>>> 'it is a "dog"'
'it is a "dog"'
>>> "it is a \"dog\""
'it is a "dog"'
字符串抑制转义
当需要打开一个文件是c:\new\test.txt的时候会出现转义导致无法成功打开的情况这个时候就需要使用raw来实现字符串抑制转义。
file=open(r'c:\new\test.txt','w')
扩展分片
>>> s='spamopen'
>>> s[0:5:2]
'sao'
从第一位开始一直到第五位元素每隔两位索引一次
步进
>>> a="hello"
>>> a[::-1]
'olleh'
边界反转
>>> b="fdsieworit"
>>> b[5:1:-1]
'weis'
字符串转换工具
>>> s=12
>>> b='23'
python不允许任何字符串同数字相加,即时b看起来像是数字也不行~!
>>> s+b
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
字符串转成数字
>>> s+int(b)
35
数字转成字符串
>>> str(s)+b
'1223'
字符串代码转换
>>> ord('s')
115
>>> chr(115)
's'
>>> o=chr(ord('s')+1)
>>> o
't'
>>> ord('t')
116
修改字符串
>>> s='spam'
>>> s=s[1:2]+'bug'+s[1:3]
>>> s
'pbugpa'
字符串格式化
>>> '%s %d %s %d' % ('bu',3,'bu',4)
'bu 3 bu 4'
>>> o='hi'
>>> 'i say %s' % o
'i say hi'
基于字典的字符串格式化
>>> l="""
... Hello %(name)s!
... your age is %(age)d!
... 
... """
>>> 
>>> 
>>> 
>>> 
>>> d={'name':'bob','age':40}
>>> 
>>> 
>>> 
>>> print l % d

Hello bob!
your age is 40!

字符串方法
方法调用就是两次操作:一是属性获取二是函数调用
属性获取:
具有object.attribute格式的表达式,含义是object中的attribute的值
函数调用:
具有函数(参数)格式的表达式意味着“调用函数代码,传递零或者更多用逗号隔开的参数对象,最后返回函数的返回值”

阅读(6572) | 评论(0) | 转发(0) |
0

上一篇:2010.11.5

下一篇:python学习记录(第四天)

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