So I just learned how to manipulate single letters in a for loop from code academy.
But let's say I made a function and wanted this function to manipulate the vowels of an user inputted word and replace the vowel with four consecutive copies of itself. How would I go about that?
Expected output:
>>>Exclamation("car")
caaaar
>>>Exclamation("hello")
heeeelloooo
So far I have:
word = input("Enter a word: ")
vowels= ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for char in word:
if char in vowels:
print(____,end='') #here I am unsure of how to replace it with consecutive copies of itself
else:
print(char,end='')
Your print statement can be:
print(4 * char,end='') # Or how many ever times you want to repeat it.
If word is 'car', this code:
>>> for char in word:
... if char in vowels:
... print(4 * char, end='')
... else:
... print(char, end='')
...
prints
caaaar
Note: You can include only the lower case vowels in your vowels list and in your if condition, check if char.lower() is in vowels.
Related
so I'm trying to write a code that will check each word in a string if there is a vowel in the beginning. If there is a vowel (upper or lowercase) then it will return the word and "-way" appended. If it begins with a consonant, then it moves the first letter to the back and appends "-ay"
Ex: anchor = anchor-way, computer = omputer-cay
.This is what I have but it seems like it's returning all words with these conditions and it's not checking for vowels. What am I doing wrong?
def pig_latin(text):
say = []
vowel = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
words = text.split()
for vowel in words:
vowel = vowel[0:] + "-way"
say.append(vowel)
if vowel not in words:
vowel = vowel[1:] + "-" + vowel[0] + "ay"
say.append(vowel)
return " ".join(say)
if __name__ == '__main__':
result = pig_latin("hi how are you")
print(result)
When you write for vowel in words:, you aren't checking for vowels in words or doing any comparison. The expression for i in iterable: is a loop that will one-at-a-time set (in this case) i to each item in the iterable. In your case, it is setting the variable vowels to the first, then second, then third, ... item in your list called words. That is, it is overwriting your vowel list you created.
Try something like this.
def pig_latin(text):
say = []
vowel = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
words = text.split()
for word in words: # loop over each word in the list of words
if word[0] in vowel: # compare the first letter of the word against the vowel list
new_word = word + '-way'
else:
new_word = word[1:] + '-' + word[0] + 'ay'
say.append(new_word)
return " ".join(say)
if __name__ == '__main__':
result = pig_latin("hi how are you")
print(result)
there are a few things that you can do.
use the lower() function.
do not confuse vowels for words.
use enumerate to edit the existing list at the correct index.
This is a working version:
def pig_latin(sentance: str):
words = sentance.split()
vowels = ['a','e','i','o','u']
for i, word in enumerate(words):
if word[0].lower() in vowels:
words[i] = word + '-way'
else:
words[i] = word[1:] + '-' + word[0] + 'ay'
return words
r = pig_latin("hi how are you")
print(r)
returns
['i-hay', 'ow-hay', 'are-way', 'ou-yay']
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:
letters = ['R', 'E', 'T', 'O', 'P', 'A']
letters = ['R', 'E', 'T', 'O', 'P', 'A']
final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]
Does anybody have an idea of how to do that?
Thank you in advance!
You can use this way to solve the problem.
letters = ['R', 'E', 'T', 'O', 'P', 'A']
words_list = ["TOP", "CUT", "REPORT", "GOOD"]
final_list = [word for word in words_list if set(word).issubset(set(letters))]
print(final_list)
In this code, we are checking each word in the words_list whether that word is made of letters in the letters_list. To do that we use the issubset method.
set(word).issubset(set(letters)) this part of code is return a boolean value. We include that word to final_list if and only if that boolean value is True.
You are almost there, you just need to tweak your all condition a bit.
all(word for letter in letters if letter in word) -> this would return True as long as any word is True which would always be the case.
What we want to check is that "all letters in the word are part of letters", letter in letters in the following code would return True/False if a letter is in letters. So with all, it would only return True if all letter in letters checks return True.
letters = ['R', 'E', 'T', 'O', 'P', 'A']
dictionary = ['REPORT', 'INVALID', 'ROPE']
final_list = [word for word in dictionary if all(letter in letters for letter in word)]
print(final_list)
outputs -
['REPORT', 'ROPE']
You can use the filter() method in python
letters = ['R', 'E', 'T', 'O', 'P', 'A']
my_lis = ['jake','jill','tim','vim']
def foo(x):
for words in x:
for letter in words:
print(letter)
if letter in letters:
return True
else:
return False
final = filter(foo,my_lis)
for x in final:
print(x)
You can filter your list using python filter() method.
Basically, I have a text file. I need to be able to check each word in the text file to see if the word starts with a vowel or consonant.
I used this code to read and then split the file into a list of words:
with open("textfile.txt") as file:
text = file.read()
text = text.split()
However from this, I am unsure how to drill down to the letter level and make the vowel/consonant check on each word. How do I check the first letter of each word in the list to see if it is a vowel or consonant?
This post tells me how to check for vowels:
checking if the first letter of a word is a vowel
So my question really is, how do I make the check on the word/letter level?
Thanks!!
A string, alike any other sequence in Python, is subscriptable.
So for a word, you can get the first letter by doing word[0]
Then, from other other post you already know, how to check if it is vowel or consonant.
You can do that for every word in your text by looping over them.
words_starting_with_vowels = []
words_starting_with_consonants = []
vowels = ['a', 'e', 'i', 'o', 'u']
for word in text: # loop over all words
lower_case_letter = word[0].lower()
if lower_case_letter in vowels:
words_starting_with_vowels.append(word)
else:
words_starting_with_consonants.append(word)
You need to select the first character in your word and compare it against an array of vowels, or you can use the startswith() method:
vowels = ('a','e','i','o','u','A','E','I','O','U')
if text.startswith(vowels):
print("starts with vowel")
else:
print("starts with consonant")
text.split() will return an array of words. You need to iterate over this and check if each word starts with a vowel.
for word in text:
if word.startswith(('A', 'a', 'E', 'e', 'I', 'i', 'O', 'o', 'U', 'u')):
print("It's a vowel") # Or do something else with the word
else:
print("Not a vowel")
Instead of word.startswith() You could also use the solution in the post you linked.
for word in text:
if word[0].lower() in ['a', 'e', 'i', 'o', 'u']:
print("It's a vowel")
else:
print("Not a vowel")
Pig Latin translator is basically an introductory code for many projects, and it involves getting words that start with consonants to move the first letter to the end of the word and add 'ay', and adding only 'ay' to a word that starts with a vowel. I have basically finished the whole project except for some places, and one main thing is getting the program to complete a whole sentence with a for loop, especially in moving to the next list item
I have tried to do simple things such as n+1 at the end of the for loop, and researched online (majority on Stackoverflow)
latin = ""
n = 0
sentence = input ("Insert your sentence ")
word = sentence.split()
first_word = word [n]
first_letter = first_word [0]
rest = first_word [1:]
consonant = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z')
vowel = ['a', 'e', 'i', 'o', 'u')
for one in consonant :
latin = latin + " " + rest + one + "ay"
print (latin)
n + 1
for one in vowel :
latin = latin + " " + first_word +ay
print (latin)
n + 1
There was no error message, however, the computer ran the variable 'one' not as the first (zeroth) letter of the variable first_word, rather, just running it from a - z. Is there anyway to fix this? Thank you
#!/usr/bin/env python
sentence = input("Insert your sentence ")
# don't forget "y" :)
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
# this empty list will hold our output
output_words = list()
# we'll take the user's input, strip any trailing / leading white space (eg.: new lines), and split it into words, using spaces as separators.
for word in sentence.strip().split():
first_letter = word[0]
# check if the first letter (converted to lower case) is in the consonants list
if first_letter.lower() in consonants:
# if yes, take the rest of the word, add the lower case first_letter, then add "ay"
pig_word = word[1:] + first_letter.lower() + "ay"
# if it's not a consonant, do nothing :(
else:
pig_word = word
# add our word to the output list
output_words.append(pig_word)
# print the list of output words, joining them together with a space
print(" ".join(output_words))
The loop loops over each word in the sentence - no need to count anything with n. There's also no need to loop over the consonants or the vowels, all we care about is "does this word start with a consonant" - if yes, modify it as per your rules.
We store our (possibly) modified words in an output list, and when we're done, we print all of them, joined by a space.
Note that this code is very buggy - what happens if your user's input contains punctuation?
I opehay hattay elpshay, eyuleochoujay
This question already has answers here:
Loop "Forgets" to Remove Some Items [duplicate]
(10 answers)
Closed 8 years ago.
I'm going through some exercises in CodeAcademy. In one they ask you to write a function to remove all the vowels from a string.
Apparently my function works with different texts, but it's not working with: "Hey look Words!". That's weird. Which could be my error?
My code:
def anti_vowel(text):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
letters = []
for char in text:
letters.append(char)
for i in vowels:
for j in letters:
if i==j:
letters.remove(j)
new_text = ''.join(letters)
print new_text
Your problem is that you are modifying letters while iterating over it. Instead, try building a new list (and a few other changes):
no_vowels = []
for j in letters:
if j not in vowels:
no_vowels.append(j)
new_text = ''.join(no_vowels)
You can always do like this. You have to use another variable for new string.
>>> vowels = ['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']
>>> string = "Hey look Words!"
>>> new_string = ""
>>> for s in string:
if s not in vowels:
new_string += s
>>> print new_string
Hy lk Wrds!