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

python查找指定字符

作者:世界哪有真情   发布日期:2026-01-24   浏览:32

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

def find_char(s, target):
    """
    查找字符串 s 中所有出现的指定字符 target 的位置。

    参数:
    s -- 要查找的字符串
    target -- 指定字符

    返回:
    一个包含所有目标字符位置的列表,如果没有找到则返回空列表
    """
    positions = []
    for i in range(len(s)):
        if s[i] == target:
            positions.append(i)
    return positions

# 示例用法
s = "hello world"
target = "o"
result = find_char(s, target)

# 输出结果
print(f"字符 '{target}' 在字符串 '{s}' 中的位置: {result}")

解释说明:

  1. 函数定义find_char(s, target) 函数用于查找字符串 s 中所有出现的指定字符 target 的位置。
  2. 参数
    • s 是要查找的字符串。
    • target 是要查找的目标字符。
  3. 返回值:返回一个列表,包含所有目标字符在字符串中的索引位置。如果未找到目标字符,则返回空列表。
  4. 示例用法:通过调用 find_char("hello world", "o"),我们可以找到字符 'o' 在字符串 "hello world" 中的所有位置,并打印出来。

希望这个示例对你有帮助!

上一篇:python中input()函数的作用

下一篇:python strptime

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

python中的yield

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

Laravel 中文站