Python capitalize()方法
将字符串的第一个字母变成大写,其他字母变小写。对于 8 位字节编码需要根据本地环境。
>>>s = 'a, B'
>>> s.capitalize()
'A, b'
>>> s = ' a, B' # a 前面有空格
>>> s.capitalize()
' a, b'
>>> s = 'a, BCD'
>>> s.capitalize()
'A, bcd'
Python center()方法
返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。
>>>str = 'runoob'
>>> str.center(20, '*')
'*******runoob*******'
>>> str.center(20)
' runoob '
Python count()方法
用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
str = "this is string example....wow!!!";
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
输出
str.count(sub, 4, 40) : 2
str.count(sub) : 1
Python Counter()方法
与count()方法类似,可以统计列表元素或字符串字母出现的个数,需要导入包。
from collections import Counter
c = Counter('sadasfas')
print(c)
a=['su','bu','sum','bu','sum','bu']
c = Counter(a)
print(c)
c.update('sadasfas') #添加
print(c)
输出
Counter({'s': 3, 'a': 3, 'd': 1, 'f': 1})
Counter({'bu': 3, 'sum': 2, 'su': 1})
Counter({'bu': 3, 's': 3, 'a': 3, 'sum': 2, 'su': 1, 'd': 1, 'f': 1})
Python decode()方法和Python encode()方法
decode()方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。 encode()方法与decode()方法类似,不过是编码字符串。
str = "this is string example....wow!!!";
str = str.encode('base64','strict');
print "Encoded String: " + str;
print "Decoded String: " + str.decode('base64','strict')
输出
Encoded String: dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=
Decoded String: this is string example....wow!!!
Python endswith()方法
用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。下标从1开始计算。
str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix);
print str.endswith(suffix,20);
suffix = "is";
print str.endswith(suffix, 2, 4);
print str.endswith(suffix, 2, 6);
输出
True
True
True
False
Python find()方法
检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
str1 = "this is string example....wow!!!"
str2 = "exam"
print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
输出
15
15
-1
Python deque()方法
为了高效实现插入和删除操作的双向列表,适合用于队列和栈
>>> from collections import deque
>>> q = deque(['a', 'b', 'c'])
>>> q.append('x')
>>> q.appendleft('y')
>>> q
deque(['y', 'a', 'b', 'c', 'x'])