Home > other >  How can i sort for every word in a string for every string in a list?
How can i sort for every word in a string for every string in a list?

Time:12-25

For starters i did this

text = "Hello I want to make this code better"

x = text.split()

sorted_characters = sorted(x[5])

sortedword = "".join(sorted_characters)

print(sortedword)

I want the code to do this but i couldn't figure out how to seperate words and every string in list:

example=['I like python', 'I like reading books']

Output should be ['I eikl hnopty', 'I eikl adeginp bkoos']

CodePudding user response:

A one liner: [' '.join([''.join(sorted(z)) for z in i.split()]) for i in example]

This just does what you did, with the list comperhension feature of python, and sort every element in the list

CodePudding user response:

You can use split to get the words out of the sentence and sort each of them and add them to a new string, like this...

text = "Hello I want to make this code better"
res = ""

for i in text.split():
    temp = ""

    for j in sorted(i):
        temp  = j

    res  = f"{temp} "

print(res)
  • Related