字符串的操作,以及常用的函数举例
1、 对字符串的修改都会产生新串,原串不变
2、原生字符串(正则基础)
path = "D:\steam\1appcache" 结果为:D:\steamappcache 出错
path = "D:\\stam\\1appcache" 结果为:D:\stam\1appcache
path = r"D:\stam\1appcache" 原生字符串,反斜杠不代表转义 结果为:D:\stam\1appcache
3、通用操作
拼接、重复、成员操作,没有增删改操作
4、字符串常用函数
1)字符串查找和替换
str1 = 'a fox jumped over the fence.the dog the pig '
print(str1.find("a", 5, 7)) # find(要检查的字符串,start=0,end=len(str)) 从左到右查找
# rfind 从右向左查找 返回一个下标, 不存在返回-1
print(str1.index("a", 5, 7)) # 与find用法相同,查询失败会报错,find返回-1
print(str1.count("o", 2, len(str1))) # count(要检查的字符串,start=0,end=len(str)) 指定字符串出现的次数
print(str1.replace("the", "an", 2)) # replace(old_str,new_str,count) 用new_str替换old_str,count是替换的次数
2)字符串分割和组合
print(str1.split(" ", 3)) # split(分隔符,分割次数),分割次数,默认是全部分割
str2 = 'ab c\n\nde fg\rkl\r\n'
print(str2.splitlines(True)) # splitlines(参数) 拆分包含多行的字符串,每行的一个元素返回一个列表。
# 当参数为非0整数或者True 时,保留行尾标志,即为换行符,否则不保留
str3 = ['a','b','c']
str = "+"
print(str.join(str3)) # a+b+c join 以str为分隔符,将join括号中所有的元素合并成一个新的字符串
str4 = 'a fox jumped over the fence.the dog the pig '
print(str4.partition("over")) # partition(分隔符) 结果为元组,分隔符前面的为一个元素,分隔符为一个,分隔符后面的为一个元素
3)字符串判断
str1 = 'adasdwe2324'
print(str1.isalpha()) # 判断字符串是否只由字母构成,是返回True,否则返回False
print(str1.isalnum()) # 判断字符串是否由数字或字母构成,是返回True,否则返回False
str2 = '12234'
str3 = b'23'
print(str2.isdigit()) # 判断字符串是否由数字构成,可以判断byte
print(str3.isdigit()) # True
print(str2.isdecimal()) # 也可以判断数字,但不能判断byte
str4 = '二'
print(str4.isnumeric()) # 可以判断数字和中文数字
str5 = ' '
print(str5.isspace()) # 判断字符串只有空格和tab组成
str6 = 'qwssdf'
print(str6.islower()) # 判断字符串中是否都是小写字母
print(str6.isupper()) # 判断字符串中是否都是大写字母
str7 = 'a fox jumped over the fence.the dog the pig'
print(str7.startswith("o",3,10)) # ⽤于判断字符串是否以指定⼦字符串开头,如果是则返回True,否则返回False。
print(str7.endswith("g",0,len(str7))) # ⽤于判断字符串是否以指定⼦字符串结尾,如果是则返回True,否则返回False
4)字符串转换
str1 = 'qwer'
print(str1.upper()) # 小写转大写
str2 = 'ASDW'
print(str2.lower()) # 大写转小写
str3 = 'asdWEREWR'
print(str3.swapcase()) # 小写转大写,大写转小写
print(str3.capitalize()) # 字符串第一个字符转大写,其他转小写
str4 = 'a fox jumped over the fence.the dog the pig'
print(str4.title()) # 字符串中每个单词的⾸字⺟⼤写,其余⼩写
str5 = ' dsf '
print(str5.strip()) # 去除字符串左边指定的字符,默认是去除空格
print(str5.lstrip()) # 去除字符串左边指定的字符,默认是去除空格
print(str5.rstrip()) # 去除字符串右边指定的字符,默认是去除空格
5)其他方法
1> str() 将其他类型转换为字符串
2> ord() 返回字符对应的码值
print(ord('a')) # 97
3> chr() 输入一个unicode码,返回一个对应的字符
print(chr(20013)) # 中
5、格式化操作
1)%
2)format
把format参数中参数名是a替换{a}, 参数名 = 值
res = "a={a},b={b},c={c}".format(c=c,a=a,b=b)
res= f"a={a},b={b},c={c}" python 3.7
str1 = 'I am {:^5}, age {:>10d}'.format("浅语呀",18)
print(str1)
6、字节字符串 :只能表示ascii(0-255) 用在签名加密
1)字符串转字节
password = "234" # Python字符串
res = password.encode("utf8") # 字节型字符串
print(type(res))
res = hashlib.sha1(res).hexdigest()
print(res)
2)字节字符串转Python字符串
b2 = "hello"
res = b2.decode("utf8")
print(res)