#!/usr/bin/env python3 #_*_ coding: utf-8 _*_ __author__ = 'GonnaZero' import sys un = sys.getdefaultencoding() print(un) def strCase(): #字符串大小转换 print("演示字符串大小转换") print("演示字符串S赋值为:'This is a PYTHON'") S = 'This is a PYTHON' print("大写转换成小写:\tS.lower() \t= %s" %(S.lower())) print("小写转换成大写:\tS.upper() \t= %s" %(S.upper())) print("大小写转换:\t\tS.swapcase() \t= %s" %(S.swapcase())) print("首字母大写:\t\tS.title() \t= %s" %(S.title())) print("\n") def strFind(): #字符串搜索替换 print("演示字符串搜索替换等") print("演示字符串S赋值为:'This is a PYTHON'") S = "This is a PYTHON" print("字符串搜索:\t\tS.find('is') \t= %s" %(S.find('is'))) print("字符串统计:\t\tS.count('s') \t= %s" %(S.count('s'))) print("字符串替换:\t\tS.replace('Is','is') = %s" %(S.replace('Is','is'))) print("去左右边空格:\t\tS.strip() \t=#%s#" %(S.strip())) print("去左边空格:\t\tS.lstrip() \t=#%s#" %(S.lstrip())) print("去右边空格:\t\tS.rstrip() \t=#%s#" %(S.rstrip())) print("\n") def strSplit(): #字符串分割,组合 print("演示字符串分割组合") print("演示字符串S赋值为:'This is a PYTHON '") S = 'This is a PYTHON' print("字符串分割:\t\tS.split() \t= %s" %(S.split())) print("字符串组合1:'#'.join(['this','is','a','python']) \t=%s" %('#'.join(['this','is','a','python']))) print("字符串组合2:'$'.join(['this','is','a','python']) \t=%s" %('$'.join(['this','is','a','python']))) print("字符串组合3:' '.join(['this','is','a','python']) \t=%s" %(' '.join(['this','is','a','python']))) print("\n") def strCode(): #字符串编码解码 #S.decode(encoding):将以encoding编码的S解码成unicode编码 #S.encode(encoding):将以 unicode编码的S编码成encoding, encoding可以是gb2312,gbk,big5等 #字符串通过编码转换为字节码,字节码通过解码转换为字符串str--->(encode)--->bytes,bytes--->(decode)--->str print("演示字符串编码解码") print("演示字符串S赋值为:'编码解码测试'") S = '编码解码测试' #以下代码及供参考,python3默认是utf-8编码 不是GBK编码 print("GBK编码的S \t = %s" %(S)) print("GBK编码的S转换 unicode编码") print("S.encode('utf-8')= %s" %(S.encode("utf-8"))) print("GBK编码的S转换成utf8") print("S.encode('utf-8').decode('utf-8') =%s" %(S.encode('utf-8').decode("utf8"))) print("注意:不管是编码还是解码针对的都是unicode字符编码,\n所以要编码或者解码前必须先将原字符串转换成unicode编码格式") print("\n") def strTest(): #字符串测试 print("演示字符串测试") print("演示字符串S赋值为:'abcd'") S = 'abcd' print("测试是否全是字母S.isalpha() = %s" %(S.isalpha())) print("测试是否全是数字S.isdigit() = %s" %(S.isdigit())) print("测试是否全是空白字符S.isspace() = %s" %(S.isspace())) print("测试是否全是小写S.islower() = %s" %(S.islower())) print("测试是否全是大写S.isupper() = %s" %(S.isupper())) print("测试是否首字母大写S.istitle() = %s" %(S.istitle())) if __name__ == '__main__': strCase() strFind() strSplit() strCode() strTest()
python3字符串操作
猜你喜欢
转载自blog.csdn.net/qq_40397452/article/details/80570128
今日推荐
周排行