How can I remove all vowels from an inputted string - python

This doesn't really work
To explain what I did:
I set a vowel variable with a list
Then I used a for loop to iterate through the list and print the letters not in the list

as user #user56700 noted: You did, probably by mistake:
if not letter.lower in vowels:
instead:
if not letter.lower() in vowels:
first is method "itself", second is call of method.
P.S.
also, as user #user56700 noted, do not screenshot and paste code as image. Just paste and format as code, it is really simple, and shows that min of respect for others :)

import re
vowel = input()
lst = re.sub("[aeiouAEIOU]","",vowel)
print(lst)

`
st=input("Enter Any String ")
vowel=['a','e','i','o','u']
#Create a List of Vowel
st=st.lower()
#Convert Vowel in Lower case
output=""
for i in st:
if i not in vowel:
#Check Vowel if not then add to output
output+=i
print(output)`

Related

Can you save strings from loops then later combine them with other strings?

So I'm (very badly) coding a hangman game in python and I've run into a bit of an issue that some google searches wouldn't seem to fix for me. So I have a string (word) and every time the user guesses a letter in this word correctly it displays the string (known_word) that displays a list of empty spaces with some being replaced by the letters they guessed in their respective places. Here is an example:
word = 'coffee'
answer = 'e'
known_word = '****ee'
After the word is displayed they are looped back to input another guess. However, when they loop back and guess another letter (correct or not) it does not display the letters that have already been guessed. Because of this, I am wondering if there is any easy way to save the value of known_word and add the new guesses to known_word so that all letters guessed so far word be displayed.
One way to do this would be to store the answers in a list. Then you can compare each character in word with the values in the answer list to generate the known_word string. For example:
word = 'coffee'
answer = ['e', 'o']
known_word = ''.join(c if c in answer else '*' for c in word)
Output:
*o**ee
If you're generating the known_word iteratively as you receive each answer, you could use a function like this to update
def update_known_word(word, answer, known_word):
for i in range(len(word)):
if(word[i] == answer):
known_word = known_word[:i] + word[i] + known_word[i+1:]
return known_word
The flow would look something like this. Typed it out step by step just for demonstration purposes but you would use a loop instead.
word = 'coffee'
known_word = '******'
# Get answer from user
answer = 'e'
known_word = update_known_word(word, answer, known_word)
print(known_word)
# Get answer from user
answer = 'c'
known_word = update_known_word(word, answer, known_word)
print(known_word)
Output:
****ee
c***ee
With a loop:
while(word_not_found):
# Get answer from user for this iteration
known_word = update_known_word(word, answer, known_word)
print(known_word)

Why for loop not processing the entire input string?

I'm new to Python coding. I am enrolled in the online course DEV274X: Introduction to Python fundamentals provided by Microsoft.
For my first assignment, I had to write a code that processes a given string and prints the words whose first letter are greater than or equal to 'h' in a new line
Only using the following methods: for/in (iteration), input, if, else, .isalpha() method, .lower() or .upper() method. The string was "Wheresoever you go, go with all your heart" and the desired output was
My code and the output I got was
Can someone help me by telling me what's wrong with this code?
I think your code is correct just a small mistake.
The last line is
print(ltr)
which will print only 't', the last iterated letter. You have to change it to 'new' and check if it is >'h'
quote="Wheresoever you go, go with all your heart"
new= ''
for letter in quote:
if letter.isalpha():
new+= letter
elif new.lower() >= 'h':
print(new.upper())
new= ''
else:
new= ''
if new.lower() >= 'h':
print(new.upper())
quote="wheresoever you go,go with your heart"
newword=""
for letter in quote:
if letter.isalpha():
newword = newword + letter
else:
print(newword)
if newword[0].lower()>='h':
print(newword.upper())
newword=""
else:
newword=""
if newword[0].lower()>='h':
print(newword.upper())
this is a typical edge condition check. Your code rely on new letter to determine current word should be print out or not. "Heart" is the last word and it should be checked at the end of for loop.

Learning Python; don't know why my function works improperly

I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to find my error:
def anti_vowel(text):
a = len(text)
b = 0
letters = []
while a > 0:
letters.append(text[b])
a -= 1
b += 1
for item in letters:
if item in "aeiouAEIOU":
letters.remove(item)
final = ""
return final.join(letters)
The issue you have is that you're iterating over your list letters and modifying it at the same time. This causes the iteration to skip certain letters in the input without checking them.
For instance, if your text string was 'aex', the letters list would become ['a', 'e', 'x']. When you iterate over it, item would be 'a' on the first pass, and letters.remove('a') would get called. That would change letters to ['e', 'x']. But list iteration works by index, so the next pass through the loop would not have item set to 'e', but instead to the item in the next index, 'x', which wouldn't get removed since it's not a vowel.
To make the code work, you need to change its logic. Either iterate over a copy of the list, iterate in reverse, or create a new list with the desired items rather than removing the undesired ones.
You'll always get unexpected results if you modify the thing that you are looping over, inside the loop - and this explains why you are getting strange values from your function.
In your for loop, you are modifying the object that you are supposed to be looping over; create a new object instead.
Here is one way to go about it:
def anti_vowel(text):
results = [] # This is your new object
for character in text: # Loop over each character
# Convert the character to lower case, and if it is NOT
# a vowel, add it to return list.
if not character.lower() in "aeiou":
results.append(character)
return ''.join(results) # convert the list back to a string, and return it.
I think #Blckknght hit the nail on the head. If I were presented with this problem, I'd try something like this:
def anti_vowel(text):
no_vowels = ''
vowels = 'aeiouAEIOU'
for a in text:
if a not in vowels:
no_vowels += a
return no_vowels
If you try it with a string containing consecutive a characters (or any vowel), you'll see why.
The actual remove call modifies the list so the iterator over that list will no longer be correct.
There are many ways you can fix that but perhaps the best is to not use that method at all. It makes little sense to make a list which you will then remove the characters from when you can just create a brand new string, along the lines of:
def anti_vowel (str):
set ret_str to ""
for ch as each character in str:
if ch is not a vowel:
append ch to ret_str
return ret_str
By the way, don't mistake that for Python, it's meant to be pseudo-code to illustrate how to do it. It just happens that, if you ignore all the dark corners of Python, it makes an ideal pseudo-code language :-)
Since this is almost certainly classwork, it's your job to turn that into your language of choice.
not sure how exactly your function is supposed to work as there are quite a few errors with it. I will walk you through a solution I would come up with.
def anti_vowel(text):
final = ''
for letter in text:
for vowel in 'aeiouAEIOU':
if (letter == vowel):
letter = ""
final += letter
print final
return final
anti_vowel('AEIOUaeiou qwertyuiopasdfghjklzxcvbnm')
We initialize the function and call the passed param text
def anti_vowel(text):
We will initialize final as an empty string
final = ''
We will look at all the letters in the text passed in
for letter in text:
Every time we do this we will look at all of the possible vowels
def anti_vowel(text):
If any of these match the letter we are checking, we will make this letter an empty string to get rid of it.
if (letter == vowel):
letter = ""
Once we have checked it against every vowel, if it is a vowel, it will be an empty string at this point. If not it will be a string containing a consonant. We will add this value to the final string
final += letter
Print the result after all the checks and replacing has completed.
print final
Return the result
return final
Passing this
anti_vowel('AEIOUaeiou qwertyuiopasdfghjklzxcvbnm')
Will return this
qwrtypsdfghjklzxcvbnm
Adding on to what the rest has already said, that you should not modify the iterable when looping through it, here is my shorter version of the whole code:
def anti_vowel(text):
return text.translate(None, "aeiouAEIOU")
Python already has a "built-in text remover", you can read more about translate here.

What is wrong with the ordering of this code?

I'm trying to make a Pig Latin translator in Python. I don't have the finished product yet and I'm working through Codecademy. Here is my code so far:
pyg = 'ay'
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
print original
if first == "a" or "e" or "i" or "o" or "u":
print "vowel"
else:
print "consonant"
else:
print 'empty'
word = original.lower()
first = word [0]
I'm pretty sure the last two lines are out of place, but I do not know where they should go and I don't know why. If anybody could explain that to me, that would be great. I'm just at the stage of this program where I want to check if the first letter is a vowel or consonant, I'm not at the translating part yet.
You're defining word and first after you check their values, so try moving those after you define original and after you check the length (to avoid an index error on empty values).
Also, where you use if len(original) > 0, you actually simplify that to if original, which will return True if it is a non-null value.
One other thing - your check for vowels will not return the expected value. Instead, try something like this:
if first in 'aeiou':
I'm sure there are better ways to handle it, but this should work for your case.
EDIT:
Changing the if statement to #Levon's method (which is much more Pythonic)
This line:
if first == "a" or "e" or "i" or "o" or "u":
Does not behave the way you expect. I actually answered basically this exact question a few days ago.
Let me know if you don't understand the explanation I gave there.
(1) Your if-statement could be rewritten in a shortened (and correct) version like this:
if first in 'aeiou':
I answered this with more explanation recently here for someone else working on the same problem as you.
(2) Re your question about where to place these two lines of code:
word = original.lower()
first = word[0]
Put them after your print original inside your if-statement. They convert your input word to lowercase, and then take the first letter of the word and assign it to the variable first which is then subsequently used to check for vowel/consonant.

Search Python list and return 2 or more of the same character

I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly guessed letters are put into at the position they are in the randomly selected word.
The problem I am having is that if the word has a letter within it more than once, it will only find the first letter and add that. How would I go about looking for all instances of a letter and adding them?
This is the code I'm using to map guessed letters against the randomly selected word.
if user_input in choose_word:
print "Good guess!"
print trys_remaining, "trys remaining!"
word_index = letter_list.index(user_input)
correct_letters[word_index] = user_input
If anyone could point me in the right direction, it would be great.
You need to loop over all matching indices:
for word_index, letter in enumerate(letter_list):
if letter == user_input:
correct_letters[word_index] = user_input
Note: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enumerate() function allows to get the index at the same time.
See also the enumerate documentation.
You can use a list comprehension:
correct_letters = [letter if user_input == letter else correct
for (correct, letter) in zip(correct_letters, letter_list)]
Note that this will create a new correct_letters list, instead
of modifying the original one.

Categories