Python3 字符串与列表常用功能
一、字符串常用功能
1. capitalize(),将字符串的首字母变成大写,其余全部置为小写;如果字符串中有多个单词,也只是将第一个单词的首字母置为大写;例:
>>> name = 'i am kevin ChOu'
>>> ret = name.capitalize()
>>> print(ret)
I am kevin chou
2.casefold(),将字符串全部置为小写
>>> name = 'II am kevin ChOu'
>>> ret = name.casefold()
>>> print(ret)
ii am kevin chou
3.center(),内容居于字符串总长度中间,其余部分用指定内容填充,默认无;其内部方法与例子如下:
#内部方法
def center(self, width, fillchar=None):''' 内容居中,width:总长度;fillchar:空白处填充内容,默认无'''
return ""
#实例
>>> name = 'kevin'
>>> ret = name.center(20,'*')
>>> print(ret)
*******kevin********
>>>
4.count(),统计子字符在指定范围内出现的次数,默认为整个字符串,也可以指定起始的索引范围;例:
>>> name = 'basketball'
>>> ret = name.count('a')
>>> print(ret)
2
>>> print(name.count('s'))
1
>>> print(name.count('a',0,5))
1
5.endswith(),是不是已'xx'字符结束;startswith(),是不是以'xx'字符开始;两者都可以指定起始的索引范围。例:
>>> name = 'basketball'
>>> print(name.endswith('l'))
True
>>> print(name.endswith('al'))
False
>>> print(name.endswith('e',0,4))
False
>>> print(name.endswith('e',0,5))
True
>>> print(name.startswith('b'))
True
>>> print(name.startswith('a',1,))
True
>>> print(name.startswith('a',2,6))
False
>>> print(name.startswith('as',0,6))
False
>>> print(name.startswith('as',1,6))
True
示例
6.expandtabs(),将tab转换成空格,默认一个tab转换成8个空格;
>>> name = 'ke\tvin'
>>> ret = name.expandtabs()
>>> print(ret)
ke vin
7.find() 返回子串在指定范围内首次出现的位置,未查到返回-1。例如:
>>> name = 'basketball'
>>> print(name.find('a'))
1
>>> print(name.find('x'))
-1
>>> print(name.find('b',1,))
6
8.index()返回子串在指定范围内首次出现的位置,未查到抛出异常。例如:
>>> name = 'basketball'
>>> print(name.index('a'))
1
>>> print(name.index('x'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> print(name.index('b',1,))
6
9.isalnum()判断字符串是否全是字母和数字(要么全是字母,要么全是数字,要么全是数字和字母)例如:
>>> str1 = 'x5y'
>>> str2 = 'ab4$'
>>> print(str1.isalnum())
True
>>> print(str2.isalnum())
False
10.isalpha()方法判断字符串内容全是字母。例如:
>>> str1 = 'Myname'
>>> str2 = 'myageis25'
>>> str3 = 'my name'
>>> print(str1.isalpha())
True
>>> print(str2.isalpha())
False
>>> print(str3.isalpha())
False
11.isdecimal()和isnumeric()判断字符串是否全是数字,该字符串必须是unicode object。例如:
>>> str1 = u'123456'
>>> str2 = u'myageis25'
>>> print(str1.isdecimal())
True
>>> print(str2.isdecimal())
False
12.isdigit()判断字符串全部为数字。例如:
>>> str1 = '123456'
>>> str2 = 'myageis25'
>>> print(str1.isdigit())
True
>>> print(str2.isdigit())
False
13.islower()判断字符串中所有的字母是否都是小写。 isupper() 判断字符串中所有的字母是否都是大写。例如:
>>> str1 = "THIS is string example....wow!!!";
>>> print( str1.islower());
False
>>> str2 = "this is string example....wow!!!";
>>> print( str2.islower());
True
14.isspace()判断字符串是否全是空白符,例如:
>>> str1 = "\t\n\r"
>>> print(str1.isspace())
True
>>> str2 = "this "
>>> print(str2.isspace())
False
15.istitle()判断字符串中,每个单词的首字母是否都是大写。例如:
>>> name = 'My name is kevin'
>>> name1 = 'My Name Is kevin '
>>> print(name.istitle())
False
>>> print(name1.istitle())
True
16.join()通过特殊字符把字符串连接起来,例如: