本文共 4007 字,大约阅读时间需要 13 分钟。
本文将逐一分析 Python 中常用的字符串操作函数,帮助开发者更高效地处理字符串数据。
str.index(sub, start=None, end=None)作用:查看子字符串 sub 是否存在于当前字符串中。如果存在则返回其第一次出现的索引位置;若不存在则抛出 ValueError 错误。
特点:
start 和 end 范围限制内不存在子字符串,会抛出错误。start 和 end,则默认从字符串开头开始搜索,直到末尾。示例:
str = "helloworldhhh"print(str.index("h")) # 输出: 0print(str.index("hhh")) # 输出: 7# print(str.index("test")) # 输出: 直接报语法错误:ValueError: substring not found 执行结果:
010
str.find(sub, start=None, end=None)作用:与 index() 函数类似,用于查找子字符串 sub 在当前字符串中的位置。与 index() 有别的是,如果找不到子字符串,find() 会返回 -1,而不会抛出错误。
特点:
-1 表示未找到。start 和 end 范围,同样会在该范围内查找。示例:
str = "helloworldhhh"print(str.find("h")) # 输出: 0print(str.find("hhh")) # 输出: 7print(str.find("test")) # 输出: -1 执行结果:
010-1
str.count(sub, start=None, end=None)作用:统计字符串中子字符串 sub 的出现次数。可以指定统计的范围 [start, end),左闭区间右开区间。
特点:
start 和 end,则默认统计整个字符串。0。示例:
str = "hello world !!! hhh"print(str.count(" ")) # 输出: 5print(str.count(" ", 5, 10)) # 输出: 1 执行结果:
31
str.split(str="", num=string.count(str))作用:将字符串按指定的 str 分割成列表。如果未指定 str,则默认按空字符串分割,这会将每个字符单独分割成一个子列表。
特点:
num 参数决定了最多分割成 num + 1 个子字符串。num 未指定,默认值为 string.count(str), 即字符串中 str 的出现次数。示例:
str = "hello world !!! hhh"print(str.split(" ")) # 输出: ['hello', 'world', '!!!', 'hhh']print(str.split(" ", 1)) # 输出: ['hello', 'world !!! hhh'] 执行结果:
['hello', 'world', '!!!', 'hhh']['hello', 'world !!! hhh']
str.strip(chars=" ")作用:移除字符串的头尾指定字符序列 chars 中的字符,默认为空格。
特点:
chars 中包含多个字符,可以同时移除多个字符。示例:
str = " hello every "print("1", str.strip(), "1") # 输出: "1 hello every 1"print(str.lstrip()) # 输出: "hello every "print("1", str.rstrip()) # 输出: "1 hello every "str = "!!! cool !!!"print(str.strip("!")) # 输出: "cool" 执行结果:
1 hello every 1hello every 1 hello every cool
str.replace(old, new, count=-1)作用:将字符串中的旧字符串 old 替换为新字符串 new。count 参数指定了最多替换次数,默认为 -1(表示替换所有可用的旧字符串)。
特点:
count 为正数,只会替换该次数内的旧字符串。示例:
str = "hello world !!! hhh"print(str.replace(" ", "-")) # 输出: "hello-world-!!!-hhh"print(str.replace(" ", "-", 1)) # 输出: "hello-world !!! hhh" 执行结果:
hello-world-!!!-hhhhello-world !!! hhh
str.join(sequence)作用:将输入序列中的元素用指定字符连接生成新的字符串。
特点:
示例:
lists = ["1", "2", "3"]tuples = ("1", "2", "3")print("".join(lists)) # 输出: "123"print("".join(tuples)) # 输出: "123"print("-".join(lists)) # 输出: "1-2-3" 执行结果:
1231231-2-3
方法:
str.upper():将字符串转换为大写字母。str.lower():将字符串转换为小写字母。示例:
str = "hello world !!! hhh"print(str.upper()) # 输出: "HELLO WORLD !!! HHH"print(str.lower()) # 输出: "hello world !!! hhh"
执行结果:
HELLO WORLD !!! HHHhello world !!! hhh
方法:
str.startswith(prefix, start=None, end=None)
作用:检查字符串是否以指定子字符串 prefix 开头。可以指定 start 和 end 范围。
示例:
str = "hello world !!! hhh"print(str.startswith("h")) # 输出: Trueprint(str.startswith("hh")) # 输出: Falseprint(str.startswith("h", 0, 5)) # 输出: True 执行结果:
TrueFalseTrue
方法:
str.endswith(self, suffix, start=None, end=None)
作用:检查字符串是否以指定子字符串 suffix 结尾。可以指定 start 和 end 范围。
示例:
str = "hello world !!! hhh"print(str.endswith("h")) # 输出: Trueprint(str.endswith("hhhh")) # 输出: Falseprint(str.endswith("h", 7, 10)) # 输出: True 执行结果:
TrueFalseTrue
方法:
str.isdigit()
作用:检查字符串是否只由数字组成。
示例:
str = "123134123"print(str.isdigit()) # 输出: True
执行结果:
true
方法:
str.isalpha()
作用:检查字符串是否只由字母组成。
示例:
str = "abc"print(str.isalpha()) # 输出: True
执行结果:
true
方法:
str.splitlines([keepends])
作用:将字符串按行分割。默认分割 \r, \r\n, 和 \n 三种换行符。如果指定 keepends,则保留换行符。
示例:
str = "123456789"print(str.splitlines()) # 输出: ['', '123', '456', '789']with open("./file1.txt", encoding="utf-8") as f: lists = f.read().splitlines() print(lists) 执行结果:
['', '123', '456', '789']['name: Jack ; salary: 12000', ' name :Mike ; salary: 12300', 'name: Luk ; salary: 10030', ' name :Tim ; salary: 9000', 'name: John ; salary: 12000', 'name: Lisa ; salary: 11000']
转载地址:http://cvkfz.baihongyu.com/