'How can I edit this code so that it prints the result a certain way?

I'm trying to get this code:

line = input("String: ")
letters = ""
words = line.split()
for word in words:
    letters = letters + word[0]
print(" ".join(letters))

String = I have a dog
Result: I h a d

To print the result like this:

I
h
a
d


Solution 1:[1]

change your print statement for this one

print("\n".join(letters))

\n is the new line character, that's why.

Solution 2:[2]

Just out of curiosity, you can reduce the code to the:

line = input("String: ")
letters = map(lambda word: word[0], line.split())
print("\n".join(letters))

Solution 3:[3]

On top of @Capies' answer. You can simplify the code to:

>>> x = "what is foo bar"
>>> "\n".join([i[0] for i in x.split()])
'w\ni\nf\nb'

Which prints as

>>> print('w\ni\nf\nb')
w
i
f
b

Explanation:

[i[0] for i in x.split()]
  • i[0] is the first letter of each word in x
  • As for i in x.split() is the iteration of words in the string x

And you then join each letter with a newline charater \n with "\n".join

Solution 4:[4]

Using list comprehension.

[print(word[0]) for word in input().split()]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Capie
Solution 2 Alexey Larionov
Solution 3 Freddy Mcloughlan
Solution 4