Python String 常用 API

来源:互联网 发布:java 断点 编辑:程序博客网 时间:2024/05/29 04:02

一、内建字符串常用API


1.1 获取字符串长度

(1) len()

该方法用于获取字符串对象的长度.

str  = "Hello"print len(str) #5

1.2 字符串分割组合

(1) split()

该方法用于使用特定字符串分割指定字符串.

str = "root:x:0:0:root:/root:/bin/bash"print str.split(":") #['root', 'x', '0', '0', 'root', '/root', '/bin/bash']
(2) join()

该方法用于使用特定的字符串来拼接指定字符串.

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()方法返回运行异常.

str = 'abca'print str.index('333')#ValueError: substring not found
(3) rfind()

该方法与find()相反,find()方法从左到右查找,rfind()方法从右到左查找.

str = 'Hello'print str.rfind('l')#3
(4) rindex()

该方法与index()相反,index()方法从左到右查找,rindex()方法从右到左查找.

str = 'Hello'print str.rindex('l')#3

(5) count()

该方法用于统计特定字符在字符串中出现的次数.

str = 'Hello'print str.count('l')#2

1.5 字符串大小写转换

(1) upper()

该方法用于将字符串转换为全大写.

str = 'Hello'print str.upper()#HELLO
(2) lower()

该方法用于将字符串转换为全小写

str = 'Hello'print str.lower()#hello
(3) capitalize()

该方法用于将字符串首字母大写

str = 'this is a string'print str.capitalize()#This is a string
(4) istitle()

该方法用于检测字符串是否为首字母大写

str = 'this is a string'print str.istitle()#False
(5) isupper()

该方法用于检测字符串是否全大写.

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()

该方法用于去掉字符串的右边空格

str = '  hello    'print str.rstrip()#"  hello"
strip()、lstrip()、rstrip()支持参数去除

str = '  hello    'print str.strip(' |o')#"hell

1.7 字符串替换

(1) replace()

该方法用于替换匹配字符串为新字符串

str = 'hello'print str.replace('o', 'TEST')#"hellTEST"

0 0
原创粉丝点击