字符串操作
简介
字符串是在每一门编程语言中都非常重要的数据类型,同时对于字符串也提供了丰富的操作函数。
下面将 Python 中提供的字符串常用函数进行分类讲解。
注意:所有的字符串操作,都不会影响原字符串本身,每次操作后都会得到一个操作后的新字符串对象
统计查找替换类
len()用来获取参数字符串的字符个数,该函数并不是字符串类型特有的,而是一个通用函数
length = len("Hello")
print(length)
length = len("Hello World")
print(length)
count()返回str在string里面出现的次数,如果start或者end指定则返回指定范围内str出现的次数格式:
count(str, start, end)
s = "hello world hello Python"
n = s.count("o")
print(n)
n = s.count("O")
print(n)
n = s.count("or")
print(n)
n = s.count("o",10,30)
print(n)
index()检测sub是否包含在string中,如果start和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则抛出一个异常格式:
index(sub, start, end)
s = "Hello"
print(s.index("l"))
print(s.index("l",0,3)) # 区间使用下标位置,左闭右开区间
print(s.index("k"))
rindex()作用同index(),查找子串时从右侧查找,若找不到会抛出一个异常格式:
rindex(sub, start, end)
s = "Hello"
print(s.rindex("l"))
print(s.rindex("l",0,3))
print(s.rindex("k"))
find()检测sub是否包含在string中,如果start和end指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1重点掌握
格式:
find(sub, start, end)
s = "Hello"
print(s.find("l"))
print(s.find("l",0,3))
print(s.find("k"))
rfind()作用同find(),查找子串时从右侧查找,若找不到返回-1格式:
rfind(sub, start, end)
s = "Hello"
print(s.rfind("l"))
print(s.rfind("l",0,3))
print(s.rfind("k"))
replace()把string中的old替换成new,如果max指定,则替换不超过max次.重点掌握
格式:
replace(old, new, max)
s = "Hello Hello Hello"
print(s.replace("ll","LL"))
print(s.replace("l","L",4))
字符串判断类
startswith()检查字符串是否是以prefix开头,是则返回True,否则返回False。如果start和end指定值,则在指定范围内检查.重点掌握
格式:
startswith(prefix, start, end)
url = "https://www.ceshiren.com"
print(url.startswith("https://"))
print(url.startswith("https://", 0, 3))
print(url.startswith("https://", 5, 30))
endswith()检查字符串是否是以suffix结束,是则返回True,否则返回False。如果start和end指定值,则在指定范围内检查.重点掌握
格式:
endswith(suffix, start, end)
url = "https://www.ceshiren.com"
print(url.endswith(".com"))
print(url.endswith(".com", 0, 20))
print(url.endswith(".com", 5, 30))
isalpha()如果string至少有一个字符并且所有字符都是字母则返回True, 否则返回False重点掌握
格式:
isalpha()
print("abc".isalpha())
print("ABC".isalpha())
print("ABCabc".isalpha())
print("123".isalpha())
print("a b".isalpha())
print("abc123".isalpha())
print("123abc".isalpha())
print("a@".isalpha())
print("".isalpha())
isdigit()如果string只包含数字则返回True否则返回False.重点掌握
格式:
isdigit()
print("123".isdigit())
print("123abc".isdigit())
print("abc123".isdigit())
print("".isdigit())
isalnum()如果string至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False格式:
isalnum()
print("abc".isalnum())
print("ABC".isalnum())
print("ABCabc".isalnum())
print("123".isalnum())
print("abc123".isalnum())
print("123abc".isalnum())
print("a b".isalnum())
print("a@".isalnum())
print("".isalnum())
isspace()如果string中只包含空格,则返回True,否则返回False.格式:
isspace()
print(" ".isspace())
print(" ".isspace()) # tab键,由4个空白组成
print("\t".isspace())
print("\n".isspace())
print("\r".isspace())
print("".isspace())
print(" a".isspace())
print("1 ".isspace())
isupper()如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False重点掌握
格式:
isupper()
print("ABC".isupper())
print("ABC123".isupper())
print("123ABC".isupper())
print("A!@#B".isupper())
print("abc".isupper())
print("abC".isupper())
print("abc123".isupper())
print("Abc!@#".isupper())
print("123".isupper())
print("".isupper())
print(" ".isupper())
islower()如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False重点掌握
格式:
islower()
print("abc".islower())
print("abc123".islower())
print("ABC".islower())
print("abC".islower())
print("Abc!@#".islower())
print("123".islower())
print("".islower())
print(" ".islower())
istitle()如果string是标题化的(所有单词首字符是大写)则返回True,否则返回False格式:
istitle()
print("Username".istitle())
print("User Name".istitle())
print("User_Name".istitle())
print("User.Name".istitle())
print("User+Name".istitle())
print("username".istitle())
print("UserName".istitle())
print("user name".istitle())
print("User name".istitle())
字符串转换类
capitalize()把字符串的第一个字符大写格式:
capitalize()
print("username".capitalize())
print("Username".capitalize())
print("userNAME".capitalize())
print("this is username".capitalize())
title()返回标题化的string,就是说所有单词都是以大写开始,其余字母均为小写格式:
title()
print("this is username".title())
print("THIS IS USERNAME".title())
print("tHIS IS username".title())
upper()转换string中的小写字母为大写重点掌握
格式:
upper()
print("abc".upper())
print("ABC".upper())
print("abCd".upper())
print("abc123".upper())
print("abc123ABC".upper())
lower()转换string中的小写字母为小写重点掌握
格式:
lower()
print("abc".lower())
print("ABC".lower())
print("abCd".lower())
print("abc123".lower())
print("abc123ABC".lower())
字符串对齐类
center()返回一个原字符串居中,并使用空格填充至长度width的新字符串,如果指定fillchar参数,则使用指定字符填充,fillchar参数长度只能为1格式:
center(width, fillchar)
print("|"+"hogworts".center(20) + "|")
print("|"+"hogworts".center(5) + "|")
print("|"+"hogworts".center(20, "-") + "|")
ljust()返回一个原字符串左对齐,并使用空格填充至长度width的新字符串,如果指定fillchar参数,则使用指定字符填充,fillchar参数长度只能为1格式:
ljust(width, fillchar)
print("|"+"hogworts".ljust(20) + "|")
print("|"+"hogworts".ljust(5) + "|")
print("|"+"hogworts".ljust(20, "-") + "|")
rjust()返回一个原字符串右对齐,并使用空格填充至长度width的新字符串,如果指定fillchar参数,则使用指定字符填充,fillchar参数长度只能为1格式:
rjust(width, fillchar)
print("|"+"hogworts".rjust(20) + "|")
print("|"+"hogworts".rjust(5) + "|")
print("|"+"hogworts".rjust(20, "-") + "|")
字符串去除空白类
strip()删除string左右两侧的空白字符, 如果指定chars参数,则删除左右两侧指定的字符重点掌握
格式:
strip(chars)
print("|" + " hogworts " + "|")
print("|" + " hogworts ".strip() + "|")
print("|" + " hogworts".strip() + "|")
print("|" + "hogworts ".strip() + "|")
print("|" + " h o g w o r t s ".strip() + "|")
print("|" + "bachogwortsabc".strip("cba") + "|")
lstrip()删除string左边的空白字符, 如果指定chars参数,则删除左侧指定的字符格式:
lstrip(chars)
print("|" + " hogworts " + "|")
print("|" + " hogworts ".lstrip() + "|")
print("|" + " hogworts".lstrip() + "|")
print("|" + "hogworts ".lstrip() + "|")
print("|" + " h o g w o r t s ".lstrip() + "|")
print("|" + "bachogwortsabc".lstrip("cba") + "|")
rstrip()删除string右边的空白字符, 如果指定chars参数,则删除右侧指定的字符格式:
rstrip(chars)
print("|" + " hogworts " + "|")
print("|" + " hogworts ".rstrip() + "|")
print("|" + " hogworts".rstrip() + "|")
print("|" + "hogworts ".rstrip() + "|")
print("|" + " h o g w o r t s ".rstrip() + "|")
print("|" + "bachogwortsabc".rstrip("cba") + "|")
字符串分割类
split()以sep为分隔符分割string,如果指定maxsplit参数,则仅分割maxsplit次重点掌握
格式:
split(sep, maxsplit)
print("a-b-c-d".split("-"))
print("a-b-c-d".split("-", 2))
print("a--b-c-d".split("-"))
print("a-+b-c-d".split("-+"))
print("a b\tc\nd\re".split())
print("a b c d e".split(" ", 3))
splitlines()使用换行符\n分割 string,如果指定keepends参数,则结果中会保留\n符号格式:
splitlines(keepends)
print("a\nb\nc".splitlines())
print("a\nb\nc".splitlines(True))
partition()从sep出现的第一个位置起,把string分成一个3元素的元组(string_pre_sep,sep,string_post_sep), 如果string中不包含sep则string_pre_str == string,其余元素为空字符串格式:
partition(sep)
print("This is Hogworts".partition("is"))
print("This is Hogworts".partition("iss"))
rpartition()从右向左sep出现的第一个位置起,把string分成一个3元素的元组(string_pre_sep,sep,string_post_sep),如果string中不包含sep则string_post_str == string,其余元素为空字符串格式:
rpartition(sep)
print("This is Hogworts".rpartition("is"))
print("This is Hogworts".rpartition("iss"))
字符串连接类
+号将两个字符串连接生成一个新字符串,+号两侧必须都是字符串重点掌握
格式:
str1 + str2
print("Hello" + "World")
print("Hello" + "123")
print("Hello" + 123)
*号将字符串重复N次后生成一个新字符串格式:
str * n
print("*"* 10)
print("hello"* 10)
join()使用string连接可迭代对象中的所有元素,可迭代对象参数中的所有元素必须是字符串重点掌握
格式:
join(iterable)
print("".join(("a","b","c")))
print("-".join(("a","b","c")))
print("->".join(("a","b","c")))
print("->".join(["a","b","c"]))
print("->".join({"a","b","c"}))
print("->".join({"a":"A","b":"B","c":"C"}))
编码解码类
encode()使用encoding指定的字符集,对string进行编码,转换成二进制字符串格式:
encode(encoding)
print("abc123".encode("gbk"))
print("你好".encode("gbk"))
print("abc123".encode("utf-8"))
print("你好".encode("u8"))
decode()使用encoding指定的字符集,对string进行解码,转换成字符串对象,string必须是二进制字符串格式:
decode(encoding)
s1 = b'\xc4\xe3\xba\xc3'
s2 = b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(s1.decode("gbk"))
print(s2.decode("utf-8"))
# print(s1.decode("u8"))
# print(s2.decode("gbk"))
切片操作
对字符串按指定的范围进行截取,得到一个子字符串,指定范围时,起始下标必须小于结束下标,且子字符串不包含结束下标。
重点掌握
格式: str[start: end: step]
s = "abcdefg"
# 普通切片
print(s[0: 2])
# 省略范围
print(s[0:])
print(s[: 2])
print(s[:])
# 指定步长
print(s[::1])
print(s[::2])
# 负下标
print(s[-3: -1])
# 负步长
print(s[-1: -3: -1])
# 逆序
print(s[::-1])
总结
- 统计查找替换类
- 字符串判断类
- 字符串转换类
- 字符串对齐类
- 字符串去除空白类
- 字符串分割类
- 字符串连接类
- 编码解码类
- 切片操作