Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python查找字符串中指定字符的位置

作者:伤哖铱旧   发布日期:2026-02-11   浏览:31

# 示例代码:查找字符串中指定字符的位置

def find_char_positions(s, char):
    """
    查找字符串 s 中指定字符 char 的所有位置。

    参数:
    s (str): 要查找的字符串。
    char (str): 要查找的字符。

    返回:
    list: 包含字符出现位置的列表,如果字符不存在则返回空列表。
    """
    positions = []
    for i in range(len(s)):
        if s[i] == char:
            positions.append(i)
    return positions

# 示例用法
string = "hello world"
character = "o"
positions = find_char_positions(string, character)
print(f"字符 '{character}' 在字符串 '{string}' 中的位置: {positions}")

解释说明:

  1. 函数定义find_char_positions(s, char) 函数用于查找字符串 s 中指定字符 char 的所有位置。
  2. 参数
    • s 是要查找的字符串。
    • char 是要查找的字符。
  3. 返回值:返回一个包含字符出现位置的列表。如果字符不存在于字符串中,则返回空列表。
  4. 遍历字符串:通过 for 循环遍历字符串中的每个字符,并检查是否与目标字符匹配。如果匹配,则将该字符的位置(索引)添加到 positions 列表中。
  5. 示例用法:查找字符串 "hello world" 中字符 "o" 的位置,并打印结果。

希望这段代码和解释对你有帮助!

上一篇:python字符串单引号和双引号的区别

下一篇:python 去除换行符

大家都在看

python excel 库

python时间格式

pythoneval函数用法

列表切片操作python

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站