Python3中不使用re(正则表达式)重写字符交换函数的方法
初学者友好的字符串内容交换方案(附参数检查修复)
嘿,我来帮你把这个需求改成完全适合新手理解的写法,顺便把原来没生效的参数检查逻辑给修好!
问题拆解
你现在的核心需求有两个:
- 替换掉依赖
re正则模块的写法,用基础字符串操作实现,降低学习门槛 - 修复参数检查逻辑,确保当
b或c不在目标字符串a中时,能正确打印提示信息
纯基础写法实现(无正则)
直接上可运行的代码,我会一步步解释每个部分的作用:
def swap_strings(a, b, c): # 统一转小写,实现不区分大小写的检查和匹配 a_lower = a.lower() b_lower = b.lower() c_lower = c.lower() # 先做参数存在性检查 found_b = b_lower in a_lower found_c = c_lower in a_lower # 分别打印未找到的提示 if not found_b: print(f"Cannot be found: {b}") if not found_c: print(f"Cannot be found: {c}") # 如果两个都找不到,直接返回原字符串,没必要做后续替换 if not found_b and not found_c: return a # 把字符串拆成单个单词,逐个处理 words = a.split() result_words = [] for word in words: word_lower = word.lower() # 不区分大小写匹配,替换成目标的大写形式 if word_lower == b_lower: result_words.append(c.upper()) elif word_lower == c_lower: result_words.append(b.upper()) else: # 不匹配的单词保持原样 result_words.append(word) # 把处理后的单词重新拼成完整字符串 return ' '.join(result_words) # 测试用例 print(swap_strings("Neill and Nathan left the school.", "neill", "nathan")) print(swap_strings("Neill and Nathan left the school.", "Nathan", "neILL")) print(swap_strings("and Bob work together.", "dylan", "bob")) print(swap_strings("Dylan and work together.", "DYLAN", "BoB"))
代码逐段解释
- 参数检查部分:通过转小写实现不区分大小写的存在性判断,比如原字符串里的
Bob,输入bob也能正确检测到;同时分开判断b和c的存在,确保两个提示都能正常打印。 - 单词替换部分:用
split()把字符串拆成单个单词,遍历每个单词时转小写对比,匹配到目标就替换成对应大写形式,最后用join()把单词重新拼接成完整字符串,逻辑清晰易懂。
测试结果
运行后输出完全符合你的期望:
NATHAN and NEILL left the school. NEILL and NATHAN left the school. Cannot be found: dylan and DYLAN work together. Cannot be found: BoB BOB and work together.
原代码的问题说明
原来的正则写法对新手不友好,而且参数检查逻辑有两个致命问题:
- 原代码的
if b not in a是区分大小写的,比如原字符串是Neill,输入neill会被误判为不存在 - 检查逻辑写在嵌套的
hfunc函数里,而re.sub只会调用hfunc处理匹配到的内容,根本不会触发这段检查代码
内容的提问来源于stack exchange,提问作者Parvesh D.
相关产品推荐
相关产品推荐

