Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22872

IslandT: Python Example — Replace words within a list, and then sort the entire list and turn it into a string

$
0
0

In this example, let us create a python program that will replace words within a list, and then sort the entire list and turn it into a string. Below is the entire program.

def rewrite(word):
    return word.replace("fat","slim")

def arrange():
    whoami = ["I", "am", "old", "and", "fat", "and", "have", "no", "girl friend!"]
    return ' '.join(sorted([rewrite(word) for word in whoami]))

print(arrange()) # I am and and girl friend! have no old slim

Now let us analyze the above functions line by line.

1) The rewrite function will replace the word ‘fat’ with ‘slim’.
2) The arrange function will create a new list while replacing one of the old list items as mentioned in 1 through the for loop and then sorted the entire list and returns the string version of the sorted list.

Phew, lots of details here in the simple program, you might want to read the sorted function on another Python tutorial site to understand how this function actually works.


Viewing all articles
Browse latest Browse all 22872

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>