下面是我总结的一些常用的string 方法
#!/usr/bin/env python# -*- coding:utf-8 -*-# Author: linghanchujian# String常用应用总结Str = "ling Han chu jian"print(Str)#从左到右第一个"h"位置print(Str.index("h"))# "h"有多少个print(Str.count("h"))# 首字符大写print(Str.capitalize())# 将Str居中长度不足用"-"填充print(Str.center(50,"-"))# 判断字符串是否指定后缀结尾print(Str.endswith("jian"))#从下标10开始查找"ia"位置print(Str.find("ia",10))#将所有的大写字母变小写print(Str.lower())#所有首字母大写print(Str.title())#默认空格作为分隔符,建立列表print(Str.split())#根据指定分隔符分离成。之前,指定,之后,建立列表print(Str.partition("Han"))# 指定字符替换print(Str.replace("jian","Han"))# 将str编码成二进制Str1 = "凌寒初见"Str2 = Str1.encode("utf-8")print(Str2)#将二进制解码成strprint(Str2.decode("utf-8"))# 将字符串中name,age替换Str3 = "My name and age are {name} and {age} respectively"print(Str3.format(name="Linghanchujian",age = "22"))# 用字典替换name和ageStr4 = "My name and age are {name} and {age} respectively"print(Str4.format_map({ "name":"Linghanchujian","age":"22"}))# 将字符串里的tab转化成空格 默认是8个空格符Str5 = "My\tname"print(Str5.expandtabs())# 将字典里的字符串用指定字符连接起来Str6 = "+"Str7 = { "1","3","5"}print(Str6.join(Str7))# 判断Str是否为整型Str7 = "123"print(Str7.isdigit())#类似于加密Str8 = "Linghanchujian"Str9 = "0123456789ABCD"trantab = str.maketrans(Str8,Str9)Str10 = "My name is Chenglong";print(Str10.translate(trantab))
下面是运行结果
ling Han chu jian101Ling han chu jian----------------ling Han chu jian-----------------True14ling han chu jianLing Han Chu Jian['ling', 'Han', 'chu', 'jian']('ling ', 'Han', ' chu jian')ling Han chu Hanb'\xe5\x87\x8c\xe5\xaf\x92\xe5\x88\x9d\xe8\xa7\x81'凌寒初见My name and age are Linghanchujian and 22 respectivelyMy name and age are Linghanchujian and 22 respectivelyMy name1+5+3TrueMy DCme Bs C8eD3loD3