# 示例代码:查找字符串中指定字符的位置
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}")
find_char_positions(s, char) 函数用于查找字符串 s 中指定字符 char 的所有位置。s 是要查找的字符串。char 是要查找的字符。for 循环遍历字符串中的每个字符,并检查是否与目标字符匹配。如果匹配,则将该字符的位置(索引)添加到 positions 列表中。"hello world" 中字符 "o" 的位置,并打印结果。希望这段代码和解释对你有帮助!
下一篇:python 去除换行符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站