python 字符串可由 单引号' 或 双引号" 括起来,二者无区别;引号可用 反斜杠\ 转义
在引号前加一个 r 可以使得引号中的字符保留原义
1 2 3 4 5
| >>> print('\some\name') \some ame >>> print(r'\some\name') \some\name
|
字符串运算符
连接 ‘+’
1 2 3 4
| >>> h = 'hello' >>> w = 'world' >>> print(h+', '+w) hello, world
|
重复 ‘*’
1 2 3 4 5 6 7
| >>> h = 'hello' >>> w = 'world' >>> print((h+', '+w+'\n')*3) hello, world hello, world hello, world
|
索引、切片 ‘[]’
关于 索引 和 切片 的特性其实对于 python 其它的容器(如:list,tuple 等)同样有效。
1 2 3 4 5 6 7 8
| >>> h = 'hello' >>> w = 'world' >>> print('h[0]:', h[0], '\t|\t', 'w[2]:', w[2]) h[0]: h | w[2]: r >>> print('h[1:3]:', h[1:3], '\t|\t', 'h[:3]:', h[:3], '\t|\t', 'h[3:]:', h[3:]) h[1:3]: el | h[:3]: hel | h[3:]: lo >>> print('w[-1:1]:', w[-1:1], '\t|\t', 'w[1:-1]:', w[1:-1], '\t|\t', 'w[-4:4]:', w[-4:4]) w[-1:1]: | w[1:-1]: orl | w[-4:4]: orl
|
比较
在 python3 中,不再支持 cmp 函数。只能使用 operator 模块的函数:
| operator |
等效于传统比较运算符 |
| operator.lt(a,b) |
a < b |
| operator.le(a,b) |
a <= b |
| operator.eq(a,b) |
a == b |
| operator.nq(a,b) |
a != b |
| operator.ge(a,b) |
a >= b |
| operator.gt(a,b) |
a > b |
常用内置函数
分割
split
split(sep=None, maxsplit=-1)
其中,sep 是分隔符,默认为空格;maxsplit 是最大分割次数,默认无限次(割完所有分隔符为止)。
split(sep=None, maxsplit=-1)[n]
选取第 $n+1$ 个分片。
re.split
import re
re.split(sep, str)
其中,sep 是分隔符,可以是正则表达式,str 为待分割字符串。
re.split 同样支持取第 $n+1$ 个分片的写法。
import re
re.split(sep, str)[n]
实例
1 2 3 4 5 6 7 8 9 10 11 12
| >>> S='Never say Never' >>> print(S.split(' ')) ['Never', 'say', '', '', 'Never'] >>> import re >>> print(re.split(r'[ ]+', S)) ['Never', 'say', 'Never'] >>> print(re.split(r'[\s,;]+', 'Never,; Say,,;,, Never')) ['Never', 'Say', 'Never'] >>> print(re.split(r'[ ]+', S)[2]) Never >>> print(S.split(' ', 1)) ['Never', 'say Never']
|