字符串
1字符串常见操作方法整理2字符串其它的一些tips
1格式化输出2字符串分割替换组装
字符串
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...d" %(x,x,x)
>>> res
'integers:...1234...1234 ...001234'
>>> x =
1.23456789
>>> '%-6.2f | .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'