Python函数——查找字符串第n次出现的位置

本文介绍了一个Python函数findSubStr,该函数用于找出指定子串在字符串中第i次出现的确切位置。通过不断搜索并更新字符串,直到找到第i次出现的位置或确定子串不存在于字符串中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#返回substr在str中第i次出现的位置
def findSubStr(substr, str, i):
    count = 0
    while i > 0:
        index = str.find(substr)
        if index == -1:
            return -1
        else:
            str = str[index+1:]
            i -= 1
            count = count + index + 1
    return count - 1
### Python 字符串处理方法和函数 #### 字符串定义 字符串Python 中最常用的数据类型之一,它们可以用单引号或双引号来表示[^1]。 ```python single_quoted_string = 'Hello, world!' double_quoted_string = "Hello, universe!" ``` #### 基本字符串操作函数 ##### 拼接字符串 可以通过加号 `+` 来实现两个字符串的拼接: ```python greeting = "Hello" name = "Alice" message = greeting + ", " + name # 输出: Hello, Alice ``` ##### 分割字符串 使用 `split()` 函数可以根据指定分隔符将字符串分割成列表: ```python text = "apple,banana,cherry" fruits = text.split(",") # ['apple', 'banana', 'cherry'] ``` ##### 查找子串位置 利用 `find()` 或者 `index()` 可以找到某个子串首出现的位置;如果找不到,则 `find()` 返回 `-1` 而 `index()` 抛出异常: ```python sentence = "Welcome to the jungle." position_find = sentence.find("jungle") # position_find=11 try: position_index = sentence.index("desert") except ValueError as e: print(e) # substring not found ``` ##### 替换子串 通过 `replace(old, new)` 将旧子串替换成新子串: ```python old_text = "I like cats and dogs." new_text = old_text.replace("cats", "rabbits") # I like rabbits and dogs. ``` ##### 大小写转换 支持多种大小写的转换方式,比如全部大写、首字母大写等: ```python lowercase = "hello".upper() # HELLO uppercase = "WORLD".lower() # world capitalized = "john doe".capitalize() # John doe titlecased = "john DOE".title() # John Doe ``` #### 特殊字符处理 ##### 去除空白字符 为了去除字符串两端多余的空格或其他空白字符,可以采用 `strip()` 方法。此方法会移除开头和结尾处所有的空白字符(包括空格、制表符 `\t` 和换行符 `\n`),但不会影响中间部分的任何空白字符[^2]。 ```python trimmed_string = ' hello there! '.strip() print(trimmed_string) # hello there! ``` #### 序列转字符串 当有一个由多个项组成的序列并希望将其组合成单一字符串时,可借助于 `join()` 方法。该方法接收一个迭代器作为参数,并用给定的分隔符把各个元素连在一起形成一个新的字符串对象[^3]。 ```python words_list = ["Python", "is", "awesome"] joined_sentence = "-".join(words_list) print(joined_sentence) # Python-is-awesome ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值