一、String字符串
1.分割和合并
1.1 str1.split(str2, num)
功能:以str2为分割截取字符串,num默认为str1.count()
若给定num 后,则截取num个字符串,剩余的不再进行截取。
str1 = "how are you , i am fine thank you"
#使用空格进行分割
list1 = str1.split(" ")
print(list1)
#结果
['how', 'are', 'you', ',', 'i', 'am', 'fine', 'thank', 'you']
1.2 str1.splitlines([keepends])
功能:字符串会按照行(‘\r’,’\r\n’,’\n’)进行分割,返回一个包含各行作为元素的列表,如果参数keepends的值为False,不包含换行符,如果为True,则保留换行符。
str2 = '''how are
you ?
i am
fine
!
'''
list2 = str2.splitlines()
print(list2)
#结果
['how are', 'you ?', 'i am', 'fine', '!']
str2 = '''how are
you ?
i am
fine
!
'''
list2 = str2.splitlines(keepends=True)
print(list2)
#结果
['how are\n', 'you ?\n', 'i am\n', 'fine\n', '!\n']
1.3 str1.join(seq)
功能:以指定字符串作为分隔符,将seq中的所有元素合并成为一个新的字符串
list2 = ['you', 'are', 'very', 'great', '!']
str3 = ' '.join(list2)
print(str3)
#结果
you are very great !
str1 = "how are you , i am fine thank you"
str3 = "*".join(str1)
print(str3)
#结果
h*o*w* *a*r*e* *y*o*u* *,* *i* *a*m* *f*i*n*e* *t*h*a*n*k* *y*o*u
注意:如果连接的是字符串,则它会把字符串中的每个字符使用指定字符连接。
2.获取最大最小字符
2.1 max(str)
功能: 返回字符串str中最大的字母
str1 = "how are you , i am fine thank you"
print(max(str1))
#结果
y
2.2 min(str)
功能:返回字符串str中最小字母
str1 = "how are you , i am fine thank you"
print(min(str1))
#结果
‘ ’
注意:比较的是ASCII码值
3.字符串的替换
3.1 replace(old , new [, count])
功能:将字符串中的old替换成new,若不指定count,则默认全部替换,若指定count,则替换前count个
str1 = "how are you , i am fine thank you"
str2 = str1.replace("you" ,'me')
print(str2)
#结果
how are me , i am fine thank me
3.2 字符串映射替换
参数一:要转换的字符 参数二:目标字符
dic = str.maketrans(oldstr, newstr)
str2.translate(dic)
str5 = "aaa bbb ccc deee"
dic = str5.maketrans("ac", "21")
# a--2 c--1
str7 = "how are you ,u ewe "
print(str7.translate(dic))
#结果
how 2re you ,u ewe
#注意:很少用
4.判断字符串的开头结尾
str.startswith(str1, start=0, end=len(str))
功能:在给定的范围内判断字符串是否以给定的字符串开头,如果没有指定范围,默认整个字符串
str1 = "aaa bbb ccc deee"
print(str1.startswith("aa"))
#结果
True
str1 = "aaa bbb ccc deee"
print(str1.startswith("aa", 3, 9))
#结果
False
str.endswith(str, start=0, end=len(str))
功能:在给定的范围内判断字符串是否以指定的字符串结尾,若没有指定范围,默认为整个字符串
str1 = "aaa bbb ccc deee"
print(str1.endswith("e"))
#结果
True
str1 = "aaa bbb ccc deee"
print(str1.endswith("e", 3 ,9))
#结果
False
5.编码与解码
str.encode(encoding=”utf-8”, errors=”scrict”)
功能:字符串的编码,若不指定encoding则默认选择utf-8
str1 = "你好吗?"
data = str1.encode()
print(data)
print(type(data))
#