python中字符串的操作方法

字符串的操作方法

参考python爬虫网络实战(第二版)胡松涛

字符串的大小写转换

S.lower():#字母大写转换成小写
S.upper()#字母小写转换成大写
S.swapcase()#字母大写转换成小写,小写转换成成大写
S.title()#将首字母大写

字符串的搜索和替换

S.find(substr,[start,[end]])#返回S中出现substr的第一个字母的标号,start和end的作用相当于在S[start:end]中搜索

S.count(substr,[start,[end]]):#计算substr在S中出现的次数

S.replace(older,newstr,[count]):#把S中的older替换成newstr,count为替换的次数

S.strip([chars]):#把S两端chars中有的字符全部去掉,一般用来去掉空格

字符串的分割、组合

S.split([sep,[maxsplit]]):#以sep为分隔,把S分成一个list,maxsplit为分割的次数,默认空白字符

S.join(sep):#把sep代表的序列用S连接起来

字符串的编码和解码

S.decode([encoding]):#将以encoding编码的S解码成Unicode编码

字符串测试

S.isalpha():#S是否全是字母,至少有一个字符
S.isdigit():#是否全是数字,至少有一个字符
S.isspace():#S是否全是空白字符,至少有一个字符
S.islower():#S是否全是小写
S.isupper():#S是否全是大写
S.istitle():#S是否是首字母大写

如何实现这些方法

#-*-coding:utf-8 -*-
def strCase():
    print("演示字符串的大小写转换\n")
    S = 'i aM a CooL Boy'
    print("大写转换成小写:",S.lower())
    print("小写转换成大写:",S.upper())
    print("大小写相互转换:",S.swapcase())
    print("首字母大写:",S.title())

def strFind():
    print("字符串的替换的搜索\n")
    S = '  you are are are a stupid boy  '
    print("在S中找stupid:",S.find('stupid'))
    print("字符串are的统计:",S.count('are'))
    print("字符串are的替换(Are):",S.replace('are','Are'))
    print("去字符串中的左右空格:",S.strip())

def strSplit():
    print("字符串中的分割和组合\n")
    S = 'how time flies'
    print("字符串分割:",S.split())
    print("字符串组合:",'!'.join(['oh','ya','xi']))

def strTest():
    print("字符串测试\n")
    S = 'abcdefg'
    print("测试是否全是字母:",S.isalpha())
    print("测试是否全是数字:",S.isdigit())
    print("测试是否全是空白字符:",S.isspace())
    print("测试是否全是小写:",S.islower())
    print("测试是否全是大写:",S.isupper())
    print("测试首字母是不是大写:",S.istitle())

if __name__ == '__main__':
    strCase()
    strFind()
    strSplit()
    strTest()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值