一、内建字符串常用API
(1) len()
该方法用于获取字符串对象的长度.
str = "Hello" print len(str) #5
1.2 字符串分割组合
(1) split()
该方法用于使用特定字符串分割指定字符串.
(2) join()str = "root:x:0:0:root:/root:/bin/bash" print str.split(":") #['root', 'x', '0', '0', 'root', '/root', '/bin/bash']
该方法用于使用特定的字符串来拼接指定字符串.
lists = ['root', 'x', '0', '0', 'root', '/root', '/bin/bash'] print ":".join(lists) #root:x:0:0:root:/root:/bin/bash
1.3 字符串替换
(1) replace()
该方法用于使用特定字符来替换指定字符串.
str = 'hello word' print str.replace('word','python') #hello python
1.4 字符串查找
(1) find()
该方法用于在指定字符串中查找特定字符.返回出现第一次的角标值.否则返回-1.
str = 'abca' print str.find('a') #0
(2) index()
该方法同find()大体功能相同,唯一不同没有找到子字符串find()返回-1,index()方法返回运行异常.
(3) rfind()str = 'abca' print str.index('333')#ValueError: substring not found
该方法与find()相反,find()方法从左到右查找,rfind()方法从右到左查找.
(4) rindex()str = 'Hello' print str.rfind('l')#3
该方法与index()相反,index()方法从左到右查找,rindex()方法从右到左查找.
str = 'Hello' print str.rindex('l')#3
(5) count()
该方法用于统计特定字符在字符串中出现的次数.
str = 'Hello' print str.count('l')#2
1.5 字符串大小写转换
(1) upper()
该方法用于将字符串转换为全大写.
(2) lower()str = 'Hello' print str.upper()#HELLO
该方法用于将字符串转换为全小写
(3) capitalize()str = 'Hello' print str.lower()#hello
该方法用于将字符串首字母大写
(4) istitle()str = 'this is a string' print str.capitalize()#This is a string
该方法用于检测字符串是否为首字母大写
(5) isupper()str = 'this is a string' print str.istitle()#False
该方法用于检测字符串是否全大写.
str = 'hello' print str.isupper()#False
(6) islower()
该方法用于检测字符串是否全小写.
str = 'hello' print str.islower()#True
1.6 字符串去除空格
(1) strip()
该方法用于去掉字符串的左右空格
str = ' hello ' print str.strip()#"hello"
(2) lstrip()
该方法用于去掉字符串的左边空格
str = ' hello ' print str.lstrip()#"hello "
(3) rstrip()
该方法用于去掉字符串的右边空格
strip()、lstrip()、rstrip()支持参数去除str = ' hello ' print str.rstrip()#" hello"
str = ' hello ' print str.strip(' |o')#"hell
1.7 字符串替换
(1) replace()
该方法用于替换匹配字符串为新字符串
str = 'hello' print str.replace('o', 'TEST')#"hellTEST"