Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The second argument of python replace function

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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:

enter image description here

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?

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading