Python之String字符串(填充、查找、提取、分割和合并、替换、判断、前缀和后缀、编解码、ASCII码转换)

重点掌握:len()、count()、center()、starswith()、find()、index()、strip()、replace()、split()、join()、isdigit()、ord()、chr()

填充:center()、ljust()、rjust()、zfill()

#填充
#1.center(width[,fillchar]);返回一个指定宽度的居中的字符串,width:指填充后整个字符串的长度,
#fillchar:指需要被填充的字符串,默认为空格
#注意:相当于生成新的字符串,填充的字符必须是精确的一个字符
str1 = "hello"
print(str1.center(20))
print(str1.center(20,"#"))
#2.ljust(width[,fillchar]);返回一个指定宽度的字符串,将原字符串居左对其,width是填充之后整个字符串的长度
print(str1.ljust(20,"%"))
#3.rjust(width[,fillchar]);返回一个指定宽度的字符串,将原字符串居左对其,width是填充之后整个字符串的长度
print(str1.rjust(20,"%"))
#4.zfill(width);返回一个指定宽度的字符串,将原字符串居右对其,width是填充之后整个字符串的长度,填充以零填充
print(str1.rjust(20))

查找: find()、rfind()、index()、rindex()、max()、min()

#查找
#1.find(str[,start,end]);从左向右依次检测,str是否在原字符串中,如果存在,则返回位置
#特点:如果是查找到字符串,返回的是字符串中第一个字符所在的下标,如果找不到,则返回-1
#注意:如果有重复子字符串,则返回第一个字符所在的位置
str2 = "abcdefgh123hello"
print(str2.find("hello"))
print(str2.find("e"))
print(str2.find("yyy"))
print(str2.find("h",3,10))       #区间包头不包尾
#2.rfind();从右向左依次检测,方式同上
print(str2.rfind("hello"))
print(str2.rfind("e"))
#3.index();与find用法基本相同,但其如果查找不到,则直接报错,而不是返回-1
print(str2.index("hello"))
print(str2.index("e"))
#4.rindex()
#5.max();返回原字符串中最大字母
print(max(str2))
#6.min()
print(min(str2))

提取:strip()、lstrip()、rstrip()

#提取
#1.strip(str),使用str作为条件提取字符串,注意:只能去除两端指定的字符【trim】
str1 = "*******today is ****** a good day******"
print(str1.strip("*"))                #today is ****** a good day
#2.lstrip(),去除左边指定字符串
print(str1.lstrip("*"))               #today is ****** a good day******
#3.rstrip(),去除右边指定字符串
print(str1.rstrip("*"))               #*******today is ****** a good day

分割:split()

#分割,使用指定字符串来分割原字符串,返回一个列表【由字符串转化为列表的过程】
#1.split()
#注意:使用split进行分割时候,其中分割的字符串不能为空
str1 = "today is a good day"
print(str1.split(" "))     #['today', 'is', 'a', 'good', 'day']
str2 = "hello"            
print(str1.split(" ",2))   #num表示分隔符出现的次数:['today', 'is', 'a good day']
#2.splitlines(flag),按照换行符【\n,\r,\r\n】分割,结果为列表
#flag可写可不写,False:忽略换行符,True:保留换行符
s1 = """today
is
a
good
day"""
print(s1.splitlines(True))          #['today\n', 'is\n', 'a\n', 'good\n', 'day']

 合并:join()

#合并
#join(),将原字符串作为连接符号,将列表中的元素连接起来,作为一个字符串【列表转换为字符串】
str3 = "_"
list1 = ["zhangdan","lisi","jack"]
str4 = str3.join(list1)
print(str4)                              #zhangdan_lisi_jack

 替换 :replace()

#替换
#replace(old,new[,max]);将原字符串中的old字符串替换为new字符串,如果指定了max,则替换的次数不超过max次
#替换得到新的字符串
str1 = "today is a good day"
print(str1)                               #today is a good day
print(str1.replace("good","bad"))         #today is a bad day

str2 = "today is a good good good day"
print(str2)                               #today is a good good good day
print(str2.replace("good","bad"))         #today is a bad bad bad day
print(str2.replace("good","bad",2))       #today is a bad bad good day

判断:isalpha()、isalnum()、isupper()、islower()、istitle()、isdigit()、isnumeric()、isdecimal()、isspace()

#判断
#全部返回的值是布尔值
#1.isalpha();如果字符串至少有一个字符并且所有的字符都是字母的话,则返回True
print("".isalpha())                 #False
print("abc".isalpha())              #True
print("abc123".isalpha())           #False

#2.isalnum();如果字符串中至少有一个字符并且搜优的字符是数字或者字母的话,返回True
print("".isalnum())                 #False
print("abc%".isalnum())             #False
print("abc123".isalnum())           #True

#3.isupper();如果字符串中至少有一个包含区分大小写的字符或者数字并且所有的字符都是大写,则返回True
print("".isupper())                 #False
print("ABC".isupper())              #True
print("ABCabc".isupper())           #False
print("123".isupper())              #False
print("ABC123".isupper())           #True

#4.islower();如果字符串中至少有一个包含区分大小写的字符或者数字并且所有的字符都是小写,则返回True
print("".islower())                 #False
print("abc".islower())              #True
print("ABCabc".islower())           #False
print("123".islower())              #False
print("abc123".islower())           #True

#5.istitle();如果对应字符串中的单词是标题化的,则返回True
print("this is a test".istitle())     #False
print("This is a test".istitle())     #False
print("This Is A Test".istitle())     #True

#6.isdigit();判断字符串中是否只包含数字,如果是则返回True
print("abc123".isdigit())            #False
print("ABCabc123".isdigit())         #False
print("123".isdigit())               #True

#7.isnumeric();判断字符串中是否只包含数字字符,如果是则返回True。同上
print("abc123".isnumeric())            #False
print("ABCabc123".isnumeric())         #False
print("123".isnumeric())               #True

#8.isdecimal();判断字符串中是否只包含十进制,如果是则返回True
print("123".isdecimal())              #True
print("123e4".isdecimal())            #False

#9.isspace();判断字符串中是否只包含空格,如果是则返回True
print("abc  46".isspace())            #False
print("    ".isspace())               #True

前缀和后缀:stratswith()、endswith()

#前缀和后缀
#startswith(str[,beg=0,end=len(string)])
#判断原字符串是否是以子字符串开头的,如果beg和end指定值,则表示在指定的范围内判断
str1 = "helloghfdh"
print(str1.startswith("hello"))          #True

#endswith(str[,beg=0,end=len(string)])
str1 = "helloghfdhello"
print(str1.endswith("hello"))          #True

编解码:encode()、decode()

#编解码
#encode();将字符串转化为字节的过程
str2 = "hello 中文"
print(str2.encode())          #默认编码格式为utf-8,国际编码格式:b'hello \xe4\xb8\xad\xe6\x96\x87'
print(str2.encode("utf-8"))   #中国编码格式:b'hello \xe4\xb8\xad\xe6\x96\x87'
print(str2.encode("gbk"))     #b'hello \xd6\xd0\xce\xc4'

#decode();将字节类型转换为字符串的过程
byte1 = str2.encode("gbk")     
print(type(byte1))            #<class 'bytes'>
print(byte1.decode("gbk"))    #hello 中文

ASCII码转换:ord()、chr()

#ASCII码转换
#ord();获取字符的整数表示
print(ord("A"))
print(ord("a"))

#chr();将编码转换为对应的字符
print(chr(65))
print(chr(97))

#将“hello”转换为大写
s1 = "hello"
s2 = ""
for i in range(len(s1)):
    num = ord(s1[i])
    num -= 32
    ch = chr(num)
    s2 += ch            #字符串拼接
print(s2)

#字符串的映射;相当于字典
#maketrans(str1,str2);创建字符映射的转换表
#str1表示字符串,str2表示需要转换的目标
#translate(table)
t = str.maketrans("ac","68")
print(t)                  #{97: 54, 99: 56}  , 0是48
s3 = "hello abc"
print(s3.translate(t))    #hello 6b8

猜你喜欢

转载自blog.csdn.net/qq_38358499/article/details/89299824