# 示例代码:查找字符串中指定字符的位置
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}")
find_char(s, target) 函数用于查找字符串 s 中所有出现的指定字符 target 的位置。s 是要查找的字符串。target 是要查找的目标字符。find_char("hello world", "o"),我们可以找到字符 'o' 在字符串 "hello world" 中的所有位置,并打印出来。希望这个示例对你有帮助!
下一篇:python strptime
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站