Python字符串内建处理函数
2016-07-18 18:40
513 查看
#coding=utf-8 __author__ = 'Administrator' # 字符串处理函数 s1 = "study python string function , I love python" #获取字符串长度 print(len(s1)) #将字符串全部转换为大写 print(s1.upper()) #将字符串全部转换为小写 print(s1.lower()) #将字符串中大写转小写,小写转大写 print(s1.swapcase()) s2 = "python is ok" #获取固定长度,右对齐,右边不够用空格补齐 print(s2.ljust(30)) #获取固定长度,左对齐,左边不够用空格补齐 print(s2.rjust(30)) #获取固定长度,中对齐,中间不够用空格补齐 print(s2.center(30)) #获取固定长度,右对齐,右边不够用0补齐 print(s2.zfill(30)) #搜索指定字符串,没有返回-1,有的话返回下表开始的位置 #s1.find("要搜索的字符串",start(可选,起始位置),end(可选,结束位置)) print(s1.find("python")) print(s1.find("python",8,len(s1))) #从右边开始搜索 print(s1.rfind("python")) #统计该字符串出现的次数 print(s1.count("p")) #s1.index()g跟find()方法一样,只是查不到会抛异常 print(s1.index("python")) #字符串替换的一些方法 #t替换s1中的love为like print(s1.replace("love","like")) #替换s1中的python为scala,最后一个参数为替换的次数 print(s1.replace("python","scala",2)) #字符串去空格以及去指定字符 s3 = " i love python " #去两边空格 print(s3.strip()) #去左边空格 print(s3.lstrip()) #去右边空格 print(s3.rstrip()) s4 = "i love python" #去两边字符串 print(s4.strip("i")) #去左边字符串 print(s4.lstrip("i")) #去右边字符串 print(s4.rstrip("python")) #按指定字符分割字符串为数组 print(s1.split(" ")) #字符串判断相关 ,一下返回值全是True或者False #是否以study开头 print(s1.startswith("study")) #是否以python结尾 print(s1.endswith("python")) #是否全为字母或数字(要么全是字母,要么全是数字) print(s1.isalnum()) #是否全为字母 print(s1.isalpha()) #是否全为数字 print(s1.isdigit()) #是否全是小写 print(s1.islower()) #是否全是大写 print(s1.isupper()) #s1的首字母是否是大写 print(s1.istitle()) #编解码 #解码函数 print(type(s1)) s5 = s1.decode("utf-8") print(type(s5)) #编码函数 s6 = s1.encode("utf-8") print(type(s6)) #cmp函数用于比较两个对象s1<s2返回-1,s1>s2返回1 s1=s2返回0 print(cmp(s1,s2))
相关文章推荐
- 文成小盆友python-num11-(1) 线程 进程 协程
- leetcode 151 Reverse Words in a String (python)
- 以写代学:python实现 剪刀、石头、布游戏
- Python处理txt数据实例
- python命令行下tab键补全命令
- python变量
- python对文件的读取
- Python 小甲鱼教程 乌龟吃鱼游戏
- python正则表达式--基本用法和函数(简单实例)
- Python爬虫实战(4):豆瓣小组话题数据采集—动态网页
- python练习
- python入门——猜数字游戏
- 解决sublime Text编译python中文脚本出错
- 我的python学习--第三天
- 老司机带你用vagrant打造一站式python开发测试环境
- python魔法方法-单目运算及一般算数运算
- python中sys.exit() os._exit() exit() quit()的简单使用
- mpi学习日志(1):mpi与python
- Python的__getattr__和__getattribute__
- 习题11 提问