python中字符串内建函数之find / rfind 、index / rindex的区别

一、find(str, beg, end)/index(str, beg, end)

从左到右查找某个符号在字符串中第一次出现的位置返回正向下标(从字符串左边开始查询字符串匹配到的第一个索引)

二、rfind(str, beg, end)/rindex(str, beg, end)

从右到左查找某个符号第一次出现的位置返回正向下标(从字符串右边开始查询字符串匹配到的第一个索引) ----> 也可以说从左到右最后一次出现的位置

find(str, beg, end)、index(str, beg, end)、rfind(str, beg, end)、rindex(str, beg, end)这四个方法均可检测字符串中是否包含子字符串 str ,如果指定 beg 和 end 范围,则检查是否包含在指定范围内。beg – 开始索引,默认为 0;end – 结束索引,默认为字符串的长度find、rfind找不到元素返回-1 而 index、rindex找不到元素会报错(异常)

下面用代码来感受一下初级用法:
str_6 = 'abcaa'
print(str_6.find('a'
### Python 字符串内置函数概述 Python 提供了一系列丰富的字符串操作方法,这些方法可以直接用于处理字符串数据。以下是常见的字符串内置函数及其功能说明: #### 基本字符串函数 - **`len(s)`**: 返回字符串 `s` 的长度[^2]。 ```python s = "hello" length = len(s) # 输出为5 ``` - **`find(sub, start=0, end=len(string))`**: 查找子字符串 `sub` 在字符串中的第一个位置,如果找不到则返回 `-1`。 ```python text = "hello world" position = text.find("world") # 输出为6 ``` - **`rfind(sub, start=0, end=len(string))`**: 类似于 `find()` 方法,但它会返回最后一次匹配到的索引位置。 ```python text = "banana" last_position = text.rfind("a") # 输出为5 ``` - **`index(sub, start=0, end=len(string))`**: `find()` 功能相似,但如果未找到子字符串,则抛出异常。 ```python try: index_value = "abc".index("d") except ValueError as e: print(e) # 输出 'substring not found' ``` - **`rindex(sub, start=0, end=len(string))`**: 类似于 `index()`,但返回的是最后出现的位置。 --- #### 其他常用字符串函数 除了上述基本函数外,还有许多其他实用的方法可以用来操作字符串: - **`upper()`**: 将字符串转换成大写形式。 ```python result = "hello".upper() # 结果为'HELLO' ``` - **`lower()`**: 转换成小写形式。 ```python result = "HELLO".lower() # 结果为'hello' ``` - **`strip([chars])`**: 移除字符串两端的空白字符(默认为空格),也可以指定移除特定字符集合。 ```python cleaned_string = " hello ".strip() # 结果为'hello' custom_strip = "www.example.com".strip("wcom.") # 结果为'example' ``` - **`split(sep=None, maxsplit=-1)`**: 根据分隔符分割字符串并返回列表,默认按任意空白字符分割。 ```python words = "apple banana cherry".split() # ['apple', 'banana', 'cherry'] limited_split = "one,two,three,four".split(",", 2) # ['one', 'two', 'three,four'] ``` - **`join(iterable)`**: 使用当前字符串作为连接符来拼接可迭代对象中的元素。 ```python items = ["red", "green", "blue"] joined_text = ",".join(items) # 结果为'red,green,blue' ``` - **`replace(old, new[, count])`**: 替换字符串中的旧子串为新子串,可以选择替换次数。 ```python modified_text = "hello world".replace("world", "there") # 结果为'hello there' partial_replace = "ababa".replace("a", "A", 2) # 结果为'AbaBA' ``` --- #### 数字相关函数 虽然题目提到的内容主要涉及字符串,但也提到了一些通用数值型函数,例如: - **`abs(x)`**: 获取数字的绝对值[^1]。 ```python absolute_value = abs(-42) # 结果为42 ``` 以上列举了一些常用的字符串内置函数以及部分扩展内容,具体应用可以根据实际需求灵活组合使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值