How can I print in one single line after using a for loop
Question:
I need your help.
So, I have to separate the words of a string, then I have to sort the letters of the words alphabetically and print them out in one line.
words = "apple pumpkin log river fox pond"
words = words.split()
for i in words:
print("".join(sorted(i)))
Answers:
for i in sorted(words):
print("".join(i))
could also do something like initialize an empty string, then add each word with a empty string to space them out
You can use use:
words = "apple pumpkin log river fox pond"
words = words.split()
for i in words:
print("".join(sorted(i)),end= " ")
print("")
The "end" string will be printed after the main string. The default value for it is "n".
You can try this:
>>> words = "apple pumpkin log river fox pond"
>>> print(' '.join([''.join(sorted(w)) for w in words.split()]))
aelpp ikmnppu glo eirrv fox dnop
Here goes step by step explanation:
>>> words = "apple pumpkin log river fox pond"
>>> words_as_lists = words.split() # split between words
>>> sorted_words_as_list = [''.join(sorted(w)) for w in words_as_lists] # sort each word's chars, and let it in a list
>>> result = ' '.join(sorted_words_as_list) # join sorted words with spaces between them
>>> print(result)
aelpp ikmnppu glo eirrv fox dnop
I need your help.
So, I have to separate the words of a string, then I have to sort the letters of the words alphabetically and print them out in one line.
words = "apple pumpkin log river fox pond"
words = words.split()
for i in words:
print("".join(sorted(i)))
for i in sorted(words):
print("".join(i))
could also do something like initialize an empty string, then add each word with a empty string to space them out
You can use use:
words = "apple pumpkin log river fox pond"
words = words.split()
for i in words:
print("".join(sorted(i)),end= " ")
print("")
The "end" string will be printed after the main string. The default value for it is "n".
You can try this:
>>> words = "apple pumpkin log river fox pond"
>>> print(' '.join([''.join(sorted(w)) for w in words.split()]))
aelpp ikmnppu glo eirrv fox dnop
Here goes step by step explanation:
>>> words = "apple pumpkin log river fox pond"
>>> words_as_lists = words.split() # split between words
>>> sorted_words_as_list = [''.join(sorted(w)) for w in words_as_lists] # sort each word's chars, and let it in a list
>>> result = ' '.join(sorted_words_as_list) # join sorted words with spaces between them
>>> print(result)
aelpp ikmnppu glo eirrv fox dnop