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.
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'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)
This question already has answers here:
How to create a statement that will print out words that start with particular word? [closed]
(2 answers)
Closed 4 years ago.
so i'm trying to make a program that adds, removes, search, saves and loads a list
i have managed to make everything work apart from searching through the list for the first letters
the program will ask what letter the user wants to search for
It will then search through the list for the first letter the user inputted
All i have managed to do is:
mylist = ["hello","world","how","you","doing"]
for word in mylist:
print (word[0])
which does print out the first letters of each word
h
w
h
y
d
>>>
but what i want to do
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
the letter the user has inputted is to be searched throughout the list
after finding all the words that start with the letter,
i would like it to print out how many words it has found and then print out the words that was found with the letter the user has requested
use list comprehension with startswith
[i for i in mylist if i.startswith(letter)]
It is similar to what you are doing but you are not checking the condition like below
mylist = ["hello","world","how","you","doing"]
for word in mylist:
if word[0]==letter:
print(word)
To play safe use .lower() on strings present in list as well
mylist = ["Hello","world","how","you","doing"]
letter = 'h'
[i for i in mylist if i.lower().startswith(letter)] #["Hello","how"]
for word in list:
if input() in word:
print(word)
Something on that line. It grabs the word from the list then tests the user input against that word.
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
input a letter you would like to search 'h'
list_starting_with_letter = [i for i in mylist if i[0].lower()==letter.lower()]
list_starting_with_letter
['hello', 'how']
print('Number of such words: '+ str(len(list_starting_with_letter)))
Number of such words: 2
https://ideone.com/U6ZM2l
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
words = list(filter(lambda s: s.startswith(letter), mylist))
print( len(words) )
for w in words: print ("\n"+w)
You can use List Comprehensions:
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
result = [word for word in mylist if word.lower().startswith(letter)]
print(len(result))
print(result)
You can learn more about the power of List Comprehensions in the docs
EDIT (inspired by other answers):
Using word.startswith() instead of indexing word[0] avoids problems with empty strings.
Hope this will help you
mylist = ["hello","world","how","you","doing"]
letter = input("input a letter you would like to search ").lower()
found = [] #Result will Store
for m in mylist:
if m.startswith(letter): #It will check if the input value match with from begining of the signl world
found.append(m) # Store the value if match
print("Total Words is "+str((len(found))))
for f in found:
print("Word List :\n"+f)
I am struggling with the command .index in Python. I want to be able to enter a sentence and then Python to return the multiple indexes of the word I choose. For example if I enter the sentence "i love you you love me we all love barney" and then choose the word "love" I want it to return "2","5","9". But instead my code only will return the first one, "2".
sentence = input("Enter a sentence")
word = input("Enter the word")
position = sentence.index(word)
print(position)
Please can you help me edit this code so it return more than one index of the chosen word.
Thanks
Use enumerate (Note: the index of the first word will be 0) and split:
s = "i love you you love me we all love barney"
for word_index, word in enumerate(s.split()):
if word == "love":
print(word_index)
Output:
1
4
8
.index only return the first occurrence. You can try this:
position = [idx+1 for idx,w in enumerate(sentence.split()) if w == word]
print(position)
You can split the words in the sentence with a space and then search for a particular word.
For example:
textSplit = sentence.split(' ')
for i in range(len(textSplit)):
if textSplit[i] == word:
print i+1
indices = [i+1 for i, x in enumerate(sentence.split()) if x == word]
indices contains all the position
How to get Python to return the position of a repeating word in a string?
E.g. the word "cat" in "the cat sat on the mat which was below the cat" is in the 2nd and 11th position in the sentence.
You can use re.finditer to find all occurrences of the word in a string and starting indexes:
import re
for word in set(sentence.split()):
indexes = [w.start() for w in re.finditer(word, sentence)]
print(word, len(indexes), indexes)
And using dictionary comprehension:
{word: [w.start() for w in re.finditer(word, sentence)] for word in sentence.split()}
This will return a dictionary mapping each word in the sentence, which repeates at least once, to the list of word index (not character index)
from collections import defaultdict
sentence = "the cat sat on the mat which was below the cat"
def foo(mystr):
sentence = mystr.lower().split()
counter = defaultdict(list)
for i in range(len(sentence)):
counter[sentence[i]].append(i+1)
new_dict = {}
for k, v in counter.iteritems():
if len(v) > 1:
new_dict[k] = v
return new_dict
print foo(sentence)
The following will take an input sentence, take a word from the sentence, and then print the position(s) of the word in a list with a starting index of 1 (it looks like that's what you want from your code).
sentence = input("Enter a sentence, ").lower()
word = input("Enter a word from the sentence, ").lower()
words = sentence.split(' ')
positions = [ i+1 for i,w in enumerate(words) if w == word ]
print(positions)
I prefer simplicity and here is my code below:
sentence = input("Enter a sentence, ").lower()
word_to_find = input("Enter a word from the sentence, ").lower()
words = sentence.split() ## Splits the string 'sentence' and returns a list of words in it. Split() method splits on default delimiters.
for pos in range(len(words)):
if word_to_find == words[pos]: ## words[pos] corresponds to the word present in the 'words' list at 'pos' index position.
print (pos+1)
The 'words' consists of the list of all the words present in the sentence. Then after that, we iterate and match each word present at index 'pos' with the word we are looking to find(word_to_find) and if both the words are same then we print the value of pos with 1 added to it.
Hope this is simple enough for you to understand and it serves your purpose.
If you wish to use a list comprehension for the above, then:
words = sentence.split()
positions = [ i+1 for i in range(len(words)) if word_to_find == words[i]]
print (positions)
Both the above ways are same, just the later gives you a list.
positions= []
sentence= input("Enter the sentence please: ").lower()
sentence=sentence.split( )
length=len(sentence))
word = input("Enter the word that you would like to search for please: ").lower()
if word not in sentence:
print ("Error, '"+word+"' is not in this sentence.")
else:
for x in range(0,length):
if sentence[x]==word: #
positions.append(x+1)
print(word,"is at positions", positions)
s="hello fattie i'm a fattie too"
#this code is unsure but manageable
looking word= "fattie"
li=[]
for i in range(len(s)):
if s.startswith(lw, i):
print (i)
space = s[:i].count(" ")
hello = space+1
print (hello)
li.append(hello)
print(li)