Python replace函数第二个参数报错及[0]修复原理解析
问题解析:replace()参数类型错误的修复逻辑
错误提示
TypeError: replace() argument 2 must be str, not list
原出错代码
def replace_words(roots, sentence): for word in sentence.split(): matches = [root for root in roots if word.startswith(root)] #print(matches) if len(matches) >0: sentence = sentence.replace(word, sorted(matches, key=lambda x:len(x))) return sentence.strip()
错误原因
Python的str.replace(old, new)方法要求第二个参数new必须是字符串类型,但原代码中sorted(matches, key=lambda x:len(x))返回的是一个排序后的列表,直接把列表传给replace()就会触发类型不匹配的错误。
为什么加[0]能修复
sorted(matches, key=lambda x:len(x))的作用是把匹配到的词根按长度升序排序——通常我们需要用最短的词根来替换原单词(比如单词"unhappiness"匹配到词根"un"和"unhappy"时,优先用更短的基础词根)。sorted()的返回值是列表,比如匹配到多个词根时会得到类似["un", "unhappy"]的结果。加[0]就是取这个列表的第一个元素,也就是排序后长度最短的那个词根,这时候拿到的是字符串类型,完全符合replace()对参数类型的要求。
修复后的代码
def replace_words(roots, sentence): for word in sentence.split(): matches = [root for root in roots if word.startswith(root)] if len(matches) > 0: # 取排序后最短的词根替换原单词 sentence = sentence.replace(word, sorted(matches, key=lambda x:len(x))[0]) return sentence.strip()
内容的提问来源于stack exchange,提问作者glitch2020
相关产品推荐
相关产品推荐

