@nalan90
2017-07-28T17:31:22.000000Z
字数 2165
阅读 609
Python高效编程技巧实战
常用函数
常用操作
In [69]: name = 'zhangshuang'
## 字符串首字母大写
In [70]: name.capitalize()
Out[70]: 'Zhangshuang'
In [86]: name = 'zhang shuang'
In [87]: name.capitalize()
Out[87]: 'Zhang shuang'
## 字符串中每个单词首字母大写
In [85]: name.title()
Out[85]: ' Zhangshuang '
In [88]: name.title()
Out[88]: 'Zhang Shuang'
## 字符串拆分
In [89]: name.split()
Out[89]: ['zhang', 'shuang']
## 将字符串转化为unicode编码格式
In [71]: name.decode()
Out[71]: u'zhangshuang'
In [72]: name.isdigit()
Out[72]: False
## 判断是否以指定字符串开头
In [73]: name.endswith('shuang')
Out[73]: True
## 判断是否以指定字符串结尾
In [74]: name.startswith('zhangs')
Out[74]: True
In [75]: name = u'张爽'
## 将字符串从unicode处理成utf-8编码
In [76]: name.encode('utf-8')
Out[76]: '\xe5\xbc\xa0\xe7\x88\xbd'
In [77]: l = ['this','is','a','test','string']
## 将列表处理成字符串,以指定字符分隔
In [78]: ' '.join(l)
Out[78]: 'this is a test string'
In [79]: name = ' zhangshuang '
## 去掉首尾空格
In [80]: name.strip()
Out[80]: 'zhangshuang'
In [81]: name.lstrip()
Out[81]: 'zhangshuang '
In [82]: name.rstrip()
Out[82]: ' zhangshuang'
## 去掉最右边指定字符
In [83]: sql = 'insert into table values(a,b,c),(d,e,f),'
In [84]: sql.rstrip(',')
Out[84]: 'insert into table values(a,b,c),(d,e,f)'
## 统计指定字符串出现的次数
In [92]: name.count('a')
Out[92]: 2
## 字符串大小写转化
In [95]: name
Out[95]: 'zhang shuang'
In [94]: name.upper()
Out[94]: 'ZHANG SHUANG'
In [96]: name = 'Zhang Shuang'
In [97]: name.lower()
Out[97]: 'zhang shuang'
## 字符串查找
In [100]: name = 'zhangshuang'
In [123]: name.find('h')
Out[123]: 1
In [124]: name.find('S')
Out[124]: -1
## 字符串格式化
In [103]: 'My name is %s' % (name)
Out[103]: 'My name is zhangshuang'
In [104]: 'My name is {name}'.format(name=name)
Out[104]: 'My name is zhangshuang'
In [110]: 'My name is {name}, I am {age} years old'.format(name='zhangshuang',age=27)
Out[110]: 'My name is zhangshuang, I am 27 years old'
In [108]: 'My name is {0}, I am {1} years old'.format('zhangshuang',27)
Out[108]: 'My name is zhangshuang, I am 27 years old'
## 替换指定字符串
In [112]: name = 'zhang shuang'
In [115]: name.replace('h','S')
Out[115]: 'zSang sSuang'