常用方法
str.lower()
:将 str 字符串全部转换成小写字母,结果为一个新的字符串
str.upper()
:将字符串全部转为大写字母,结果为一个新的字符串
str.split(sep=None)
:把 str 按照指定的分隔符 sep 进行分隔,结果为列表类型
str.count(sub)
:结果为 sub 这个字符串在 str 中出现的次数
find(sub)
:结果为 sub 这个字符串在 str 中是否存在,如果不存在结果为-1,如果存在,如果出现结果为 sub 首次出现的索引
str.index(sub)
:功能与 find()相同,区别在于要查询的子串 sub 不存在时,程序报错
str.startswith(s)
:查询字符串 str 是否以子字符串 s 开头
str.endswith(s)
:查询字符串 str 是否以子字符串 s 结尾
str.replace(old,news,count)
:使用 news 替换字符串 s 中所有 old 字符串,结果是一个新的字符串
str.center(width,filllchar)
:字符串 str 在指定的宽度范围内居中,可以使用 fillchar 进行填充
str.join(iter)
:在 iter 中的每个元素后面都增加一个新的字符串 str
str.strip(chars)
:从字符串中去掉左侧和右侧 chars 中列出的字符串
str.lstrip(chars)
:从字符串中去掉左侧 chars、中列出的字符串
str.rstrip(chars)
:从字符串中去掉右侧 chars、中列出的字符串
格式化字符串的方法
占位符
%s:字符串格式 %d:十进制整数格式 %f:浮点数格式
例如
print("姓名:%s,年龄:%d,成绩:%f" % (name, age, score))
f-string
python3.6 引入的格式化字符串的方式,比{}表明被替换的字符
例如
print(f"姓名:{name},年龄:{age},成绩:{score}")
str.format()方法
模板字符串.format()
print("姓名:{0},年龄:{1},成绩:{2}".format(name, age, score))
详细格式
:
:引导字符
填充:用于填充的单个字符
对其方式:<
左对齐,>
右对齐,^
居中对齐
宽度:字符串的输出宽度
,
:字符串的千位分隔符
.精度:浮点数小数部分的精度或字符串的最大输出长度
类型:整数类型:b\d\o\x\X 浮点数类型:e\E\f%
编码与解码
字符串的编码
将 str 类型转换为 bytes 类型,需要使用到字符串的 encode()方法
语法格式:
str.encode(encoding='utf-8', errors='strict'/ignore/replace)
字符串的解码
将 bytes 类型转换为 str 类型,需要使用到 bytes 类型的 decode()方法
语法格式:
str.decode(encoding='utf-8', errors='strict'/ignore/replace)
数据的验证
str.isdigit()
:所有字符都是数字(阿拉伯数字)
str.isnumeric()
:所有字符都是数字
str.isalpha()
:所有字符都是字母(包括中文字符)
str.isalnum()
:所有字符都是数字或字母(包括中文字符)
str.islower())
:所有字符都是小写
str.isupper()
:所有字符都是大写
str.isspace()
:所有字符都是空白字符(\n,\t 等)
字符串的处理
字符串的拼接
1.使用str.join()
方法进行拼接字符串
例如
print("|".join([x,y,"ww"]))
2.直接拼接 3.使用格式化字符串进行拼接
字符串的去重
1.字符串的拼接以及 not in
for i in x: if i not in x_new: x_new += i print(x_new)
2.索引+not in 3.通过列表集合+列表排序
x_new = set(x) lst = list(x_new) lst.sort(key=x.index) print(''.join(lst))