I'm trying to make an acronym program where the user can enter 1 word per line and after entering a blank space the program will output the word created by the first letter of each word. It is printing a whitespace after the output which I don't want. Any Ideas on how to remove that? More information below:
E.g
User input:
Word: Hello
Word: World
Desired output:
Hello World <-- whitespace here that I don't want
-- HW
My Current Code that works:
words = []
word = input('Word: ')
while word:
words.append(word)
word = input('Word: ') #Word input
for word in words:
print(word, end=" ") #displays all words on one line
# Printing a white space ^
# Wanting to print this code on a new line
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("\n-- " + new)
You're almost there. Combining what you had with num and print:
for word in words:
print(word[:1], end="") # Display all first letters without spaces.
This code does everything you want
words = []
word = input('Word: ')
while word:
words.append(word)
word = input('Word: ') #Word input
print(' '.join(words))
first_letters = ''.join([word[0] for word in words])
new=first_letters.upper()
print("-- " + new)
Simply this?
words = ['Hello','World']
print(' '.join(w for w in words))
print('-- '+''.join(w[0] for w in words))
Given array of strings words. There are several approaches to get first letters of the words. Few of them are below.
First approach
first_letters = ''
for word in words:
first_letters += word[0]
print(first_letters)
Second approach
first_letters = ''.join([word[0] for word in words])
print(first_letters)
Related
I'm fairly new to Python and one of the practice projects I'm trying to do is converting sentences into pig latin. The original project was just converting words into pig latin, but I want to expand this into converting sentences.
Here's the code I have so far:
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
word = input ("Write a Word: ")
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
print ()
print ("{}".format(pig_Latin), file=sys.stderr)
end = input ("\n\n Press N\n")
if end.lower() == "n":
sys.exit()
The plan is to modify this so it splits all the words in the input sentence, converts each word to pig latin, and then spits it back out as one sentence but I'm not really sure how to do that.
I'm using Python 3.8. Any help is appreciated! Thank you.
You could split the sentence by the space character into separate strings each containing a word. You can then apply your current algorithm to every single word in that sentence. str has a method split which returns a list.
To get the words in a list, use listofwords = input('Write your sentence: ').split().
Then, you can combine the list of pig-latin words doing print(' '.join(listofpiglatin)).
import sys
print("Pig Latin Maker")
VOWELS = 'aeiouy'
while True:
listofwords = input ("Write a Sentence: ").split() # splits by spaces
listofpiglatin = []
for word in listofwords:
if word[0] in VOWELS:
pig_Latin = word + 'way'
else:
pig_Latin = word[1:] + word[0] + 'ay'
listofpiglatin.append(pig_Latin) # adds your new pig-latin word to our list
print()
print(' '.join(listofpiglatin)) # spits the words back as a sentence
end = input ("\n\n Press n")
if end.lower() == "n":
sys.exit()
I hope that this helps you learn!
Put your algorithm into a function:
def makePigLatin(word):
<your code here>
return latinWord
As other users mentioned, split the input and assign to a list:
words = input('blah').split()
Then apply your function to each word in the list:
translatedWords = map(makePigLatin, words)
Print them back out by joining them together:
print(' '.join(translatedWords))
I have this code
#Ask for word
w = input("Type in a word to create acronym with spaces between the words:")
#Seperate the words to create acronym
s = w.split(" ")
letter = s[0]
#print answer
print(s.upper(letter))
And I know that I need a for loop to loop over the words to get the first letter of each word but I can't figure out how to do it I tried many different types but I kept getting errors.
Try this. It prints a concatenated version of the first letter of each word.
w = input("Type in a word to create acronym with spaces between the words:")
print(''.join([e[0] for e in w.split()]).upper())
Try this
w = input("Type a phrase with a space between the words:")
w_up_split = w.upper().split()
acronym = ""
for i in w_up_split:
acronym += (i[0])
print(acronym)
for word in w.split(" "):
first_letter = word[0]
print(first_letter.upper())
In the code that you gave you are taking the first word in a list of lists.
s = w.split(" ")
letter = s[0]
If someone input 'Hi how are you' this s would equal
s == ["Hi"]["how"]["are"]["you"]
And then letter would equal the first index of s which would be ["Hi"]
You want to go through each word and take each letter
acronym = []
for x in s:
acronym.append(x[0])
Would get what you want.
I am trying to print each word from my list onto separate lines, however it is printing each letter onto individual lines
Words = sentence.strip()
for word in sentence:
print (word)
My full code (for anyone wondering) is:
import csv
file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.strip()
for word in sentence:
print (word)
for s in Words:
Positions = Words.index(s)+1
file.write(str(Words) + (str(Positions) + "\n"))
file.close()
You forgot to split sentence and use "Words" not "sentence" in first for loop.
#file = open("Task2.csv", "w")
sentence = input("Please enter a sentence: ")
Words = sentence.split()
for word in Words:
print (word)
for s in Words:
Positions = Words.index(s)+1
#file.write(str(Words) + (str(Positions) + "\n"))
#file.close()
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Please enter a sentence: I am Dinesh
I
am
Dinesh
C:\Users\dinesh_pundkar\Desktop>
You need to used str.split() instead of str.strip().
str.strip() only removes the leading and trailing whitespaces in a string:
>>> my_string = ' This is a sentence. '
>>> my_string.strip()
'This is a sentence.'
str.split() does what you want which is return a list of the words in the string; by default, using whitespace as the delimiter string:
>>> my_string = ' This is a sentence. '
>>> my_string.split()
['This', 'is', 'a', 'sentence.']
So, your code should look more like:
words = sentence.split()
for word in sentence:
print(word)
This question already has answers here:
How to modify list entries during for loop?
(10 answers)
Closed 6 years ago.
I'm taking a sentence and turning it into pig latin, but when I edit the words in the list it never stays.
sentence = input("Enter a sentence you want to convert to pig latin")
sentence = sentence.split()
for words in sentence:
if words[0] in "aeiou":
words = words+'yay'
And when I print sentence I get the same sentence I put in.
another way to do it (includes some fixes)
sentence = input("Enter a sentence you want to convert to pig latin: ")
sentence = sentence.split()
for i in range(len(sentence)):
if sentence[i][0] in "aeiou":
sentence[i] = sentence[i] + 'yay'
sentence = ' '.join(sentence)
print(sentence)
Because you did not change sentence
So to get the results you want
new_sentence = ''
for word in sentence:
if word[0] in "aeiou":
new_sentence += word +'yay' + ' '
else:
new_sentence += word + ' '
So now print new_sentence
I set this up to return a string, if you would rather have a list that can be accomplished as easily
new_sentence = []
for word in sentence:
if word[0] in "aeiou":
new_sentence.append(word + 'yay')
else:
new_sentence.append(word)
If you are working with a list and you want to then convert the list to a string then just
" ".join(new_sentence)
It does not seem as though you are updating sentence.
sentence = input("Enter a sentence you want to convert to pig latin")
sentence = sentence.split()
# lambda and mapping instead of a loop
sentence = list(map(lambda word: word+'yay' if word[0] in 'aeiou' else word, sentence))
# instead of printing a list, print the sentence
sentence = ' '.join(sentence)
print(sentence)
PS. Kinda forgot some things about Python's for loop so I didn't use it. Sorry
I'm trying to basically take an inputted sentence and alter each word slightly. This should work for any sentence.
So far I have this:
line = (input("Enter a sentence: "))
words = line.split()
for word in words:
new_line = 'em-' + word[1:] + word[0] + '-ma'
print(new_line)
but all this does is take the last word in the sentence and does what i want it to do. I want each word to be altered where the first letter in each word is moved to the last place, and each word is "sandwiched" by "em-" and "-ma". Any advice?
update:
what if i did this?
line = (input("Enter a sentence: "))
words = line.split( )
for word in words:
print('Result: ','em-' + word[1:] + word[0] + '-ma')
this gives me what I want but it repeats result over and over and the words are in a vertical line. how do i fix this?
new_line is being replaced every time the loop is executed so in the print statement outside of the loop it has the value of the last word.
If you just want to print each word, move the print inside the loop.
If you want all of the words accessible outside of the loop, add them all to a list or replace the loop with a list comprehension:
new_words = ['em-' + word[1:] + word[0] + '-ma' for word in words]