For one of my tasks, the user inputs multiple strings until they enter a blank line and then it prints it out in one line, this is how I did it.
words = []
word = input("Word: ")
while word:
words.append(word)
word = input("Word: ")
words = (' ').join(words)
print(words)
However, there's another part where it takes the first letter of each string in the list and prints it out in capital letters in one line. I cannot figure out how to print this on one line. This is my code:
words_split = words.split()
for word in words_split:
i = word[0]
print(i.upper())
eg If I entered ace, bravo, charlie
: it would print out
A
C
E
instead of
ACE
Can someone assist me thank you (:
Lots of possibilities, but this is how I would do it:
words_split = words.split()
print(''.join(word[0].upper() for word in words_split))
Updated my answer since @Smarx gave an identical one.
Considering:
words = "ABC BCA CAB"
This is how I'd put it:
first_letter_upper = [word[0].upper() for word in words.split()]
joined_words = ''.join(first_letter_upper)
print(joined_words)
Prints
ABC
I have another solution using Python List Comprehension i recomend read more about the method on the web.
if you have the next example:
words = 'Create a list of the first letters of every word in this string'
You can create a new list with every firts letter writing someting like that:
newlist = [x[0].upper() for x in words.split()]
print(newlist)
The correct output is:
['C', 'A', 'L', 'O', 'T', 'F', 'L', 'O', 'E', 'W', 'I', 'T', 'S']
Create an empty string outside of the for loop and add each letter to it inside the loop. Once the loop ends, print the string.
words_split = words.split()
output = ""
for word in words_split:
output += word[0].upper()
print(output)
An alternate method is to change the terminating character of the print to nothing:
words_split = words.split()
for word in words_split:
i = word[0]
print(i.upper(), end='')
your problem is that the print function going one line down after each print, to solve it you can use the end parameter:
print("a",end = '')
print("b",end = '')
will print:
ab
instead of:
a
b
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.