You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现检查字符串中'x'后续字符为'p'或'z'的Python函数

问题分析与解决方法

原代码的错误点

  • 函数定义语法错误:def find(word) 末尾缺少冒号 :,不符合Python语法规范
  • 循环遍历对象错误:for i in word 中i是单个字符,执行i+1会触发类型错误(字符串无法与整数相加)
  • 逻辑判断错误:i == 'x' and i+1 == 'p' or i+1 == 'z' 不仅存在逻辑优先级问题,也完全没实现"检查x的下一个字符"的需求
  • 返回时机错误:循环第一次迭代就直接return,无法遍历整个字符串检查所有x的情况
  • 函数调用错误:print(def('rtgxpsa')) 中def是Python关键字,不能用作函数调用,应该使用定义好的函数名find

正确实现方法

方法一:索引遍历检查

def check_x_followed(word):
    # 遍历到倒数第二个字符,避免索引越界
    for i in range(len(word) - 1):
        if word[i] == 'x':
            # 检查x的下一个字符是否为p或z
            if word[i+1] in ('p', 'z'):
                return True
            else:
                # 存在不符合条件的x,直接返回False
                return False
    # 字符串中没有x,或所有x都符合条件(无x时返回True,符合需求逻辑)
    return True

# 测试示例
y = 'rtgxpsa'
print(check_x_followed(y))  # 输出True

方法二:用find方法定位x

def check_x_followed(word):
    x_pos = word.find('x')
    while x_pos != -1:
        # 如果x是最后一个字符,或后续字符不是p/z,返回False
        if x_pos == len(word)-1 or word[x_pos+1] not in ('p', 'z'):
            return False
        # 继续查找下一个x的位置
        x_pos = word.find('x', x_pos + 1)
    # 所有x都符合条件,或无x存在
    return True

y = 'rtgxpsa'
print(check_x_followed(y))  # 输出True

边界情况说明

  • 字符串为'x':单独的x无后续字符,返回False
  • 字符串为'xz':x后是z,返回True
  • 字符串为'xa':x后是a,返回False
  • 字符串为'abcd':无x存在,返回True

内容的提问来源于stack exchange,提问作者joshki.03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:50:22