Python String 常用 API

一、内建字符串常用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"

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值