I would like to sort words in roots, and then replace the sentence by each root. The below code throw me an error
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()
But if we add [0] behind sorted( ), it will fix the error:
Looks like [0] converted the second argument of sorted function from list to string, but I really have trouble understanding what is the underlying process. Could anyone kindly explain it?
CodePudding user response:
You're overthinking the error...
Does it make sense if you write it like this?
sorted_roots = sorted(matches, key=lambda x:len(x))
sentence = sentence.replace(word, sorted_roots)
sorted()
returns a list. str.replace()
needs 2 string arguments, not a string, and a list.
By adding [0]
to the end of sorted()
, you've gotten the first element of the sorted list (the shortest root)