字符串
1、字符串常见操作方法整理
操作 | 解释 | 备注 |
---|---|---|
s = ” | 空字符串 | |
s = “spanm’s’” | 双引号和单引号相同 | |
s = ‘s\np\ta\x00m’ | 转义序列 | |
s = “”“…”“” | 三重引号字符串 | |
s = r’\temp\spam’ | Raw字符串 | |
s = b’spam’ | 一种新的常量形式b’x x x’(以及对等的B’x x x’)用来创建Python 3.0中的b y t e s对象 | |
s = u’spam’ | 在2.6中使用的unicode字符串 | |
s1 + s2 s * 3 | 合并 重复 | |
s[i] s[i:j] len(s) | 索引 分片 求长度 | |
“a %s parrot” %kind | 字符串格式化表达式 | |
“a {0} parrot”.format(kind) | 字符串格式化方法 | |
s.find(‘pa’) | 字符串方法:搜索 | 返回第一个匹配字符的位置 |
s.rstrip() | 移除右侧空格和换行符 | |
s.repalce(‘pa’,’xx’) | 替换 | |
s.split(‘,’) | 用展位符分隔 | |
s.isdigit() | 内容测试 | |
s.lower() | 短信息转换 | 大小写转换 |
s.endwith(‘spam’) | 结束测试 | s = ‘hello’ s = s + ‘spam’ print s.endswith(‘spam’) 输出为True |
‘spam’.join(strlist) | 插入分隔符 | |
s.encode(‘latin-1’) | Unicode编码等 | |
for x in s:print(x) | 迭代,成员关系 | 找出字符在h之前的字符,组成新的字符 s = ‘hellospam’ f = [] for i in s: if i < ‘h’: f.append(i) print ”.join(f) 输出为:ea |
‘spam’ in s ’spam’ not in s | 判断子字符串是否存在 | |
[c*2 for c in s] | 字符串解析 | s = ‘hellospam’ print [c*2 for c in s] 结果 [‘hh’, ‘ee’, ‘ll’, ‘ll’, ‘oo’, ‘ss’, ‘pp’, ‘aa’, ‘mm’] |
s[:] | 有效的实现顶层的完整拷贝 | 对于原地修改的对象如列表很实用 |
map(ord,s) | 以函数ord操作序列s中的每一个成员 | map(lambda x:x+’w’,’hhh’) |
2、字符串其它的一些tips
1)格式化输出
>>> x=1234
>>> res = "integers:...%d...%-6d...%06d" %(x,x,x)
>>> res
'integers:...1234...1234 ...001234'
>>> x = 1.23456789
>>> '%-6.2f | %05.2f | %+06.1f' %(x,x,x)
'1.23 | 01.23 | +001.2'
基于字典的字符串格式化
>>> reply="""
Greetings...
Hello %(name)s!
You age squard is %(age)s
"""
>>> values = {'name':'Bob','age':40}
>>> print reply %values
Greetings...
Hello Bob!
You age squard is 40
>>> food = 'spam'
>>> age = 100
>>> vars()
{'name': 'spam', '__builtins__': <module '__builtin__' (built-in)>, 'res': 'integers:...1234...1234 ...001234', 'age': 100, '__package__': None, 'food': 'spam', 'values': {'age': 40, 'name': 'Bob'}, 'x': 1.23456789, 'reply': '\nGreetings...\nHello %(name)s!\nYou age squard is %(age)s\n', '__name__': '__main__', '__doc__': None}
>>> '%(age)d,%(food)s' %vars()
'100,spam'
>>> template = '{motto},{0} and {food}'
>>> template.format('ham',motto='spam',food=[1,2])
'spam,ham and [1, 2]'
2)字符串分割、替换、组装
>>> x = '{motto},{0} and {food}'.format(42,motto=3.14,food=[1,2])
>>> x
'3.14,42 and [1, 2]'
>>> x.split('and')
['3.14,42 ', ' [1, 2]']
>>> y = x.replace('and','but under no circumstances')
>>> y
'3.14,42 but under no circumstances [1, 2]'
>>>
>>> s = 'abcdefgh'
>>> l = list(s)
>>> l
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> '&'.join(l)
'a&b&c&d&e&f&g&h'