整理:Python字符串常用函数

example = "hello nice to meet you too"
#从左向右查找指定字符串第一次出现位置
example.find("to")
#指定查找的起始、结束位置
example.find("to", 12, 20)
#从右向左查(从左向右)找指定字符串第一次出现位置
example.rfind("to") 或 example.rfind("to")
#类似find()的方法  区别:index()找不到会报错  ValueError: substring not found
example.index("to")

#统计字符串中某个子串出现的次数(不重复计数)
example.count("o")
#在指定区间内统计子串出现的次数(不重复计数)
example.count("o", 5, 10)

example = "hello nice to meet you too\nmeet you too"
#根据指定的切割符(默认为空白:包括换行、回车、空格) 对字符串进行分割 返回值为列表
example.split()
example.split("ee")
#设置最大切割次数
example.split(maxsplit = 3)
#去除字符串两端指定内容(默认去除空白)
example.strip()
str0 = "[12, 34, 56]"
res = str0.strip("[]")
#只去除左边
str0.lstrip("[")
#只去除右边
str0.rstrip("]")

#字符串格式化
print("%02d %.1f" % (2, 3.14))
#转义符\
str0 = "abc\\nm\\tvhgh\\rb"
str0 = r"abc\\nm\\tvhgh\\rb"
str0 = r"D:\课堂工具\day06\Day06"

#判断字符串是否以指定内容开头
example.startswith("hello")
#判断字符串是否以指定内容结尾
example.endswith("too")
#判断字符串的内容是否是纯英文字母
example.isalpha()
#判断字符串的内容是否是纯数字
example.isdigit()
#小写字母转换为大写字母
example.upper()
#大写英文字母转换为小写
example.lower()
#字符串中大写转化为小写 小写转换为大写  其他保持不变
example.swapcase()
#整个字符串的首字母转化为大写
example.capitalize()
#将每个单词的首字母转换为大写
example.title()
#替换 被替换的字符串 替换成的字符串 替换次数
example.replace("b", "B", 2)
#拼接  以指定拼接符拼接序列中的内容
list0 = ["10", "20", "30", "40"]
"-".join(list0)
#对字符串进行编码
example.encode("utf-8")
#对字符串进行解码
b'\xe4\xbd\xa0'.decode("utf-8")

猜你喜欢

转载自blog.csdn.net/Mithrandir_/article/details/81299284