Python字符串内建处理函数

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

 

posted @ 2016-07-18 18:40  阿伟~  阅读(1484)  评论(0编辑  收藏  举报