I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)
For now I've got this ;
sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
Something like this?
sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
The two answers are good if you want to print all the occurrences of the vowels in the sentence -- so "Hello World" would print 'o' twice, etc.
If you only care about distinct vowels, you can instead loop over the vowels. In a sense, you're flipping the code suggested by the other answers:
sentence = input('Enter your sentence: ')
for vowel in 'aeiou':
if vowel in sentence:
print(vowel)
So, "Hey there, everything alright?" would print
a e i
As opposed to:
e e e e e i a i
And the same idea, but following Jim's method of unpacking a list comprehension to print:
print(*[v for v in 'aeiou' if v in sentence])
Supply provide an a list comprehension to print and unpack it:
>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i
This makes a list of all vowels and supplies it as positional arguments to the print call by unpacking *.
If you need distinct vowels, just supply a set comprehension:
print(*{i for i in s if i in 'aeiou'}) # prints i e a
If you need to add the else clause that prints, pre-construct the list and act on it according to if it's empty or not:
r = [i for i in s if i in 'aeiou']
if r:
print(*r)
else:
print("empty")
You could always use RegEx:
import re
sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())
if len(vowels) == 0:
for i in vowels:
print(i)
else:
print("Empty")
You can always do this:
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
characters_input = input('Type a sentence: ')
input_list = list(characters_input)
vowels_list = []
for x in input_list:
if x.lower() in vowels:
vowels_list.append(x)
vowels_string = ''.join(vowels_list)
print(vowels_string)
(I am also a beginner btw)
Related
I'm trying to check if the user input contains a vowel or not. However, I've only found how to check for one vowel at a time, but not all.
vowel = ("a")
word = input("type a word: ")
if vowel in word:
print (f"There is the vowel {vowel} in your word")
else:
print ("There is no vowel in your word")
This seems to work but I get a error if I try to make the vowel variable into a list. ["a","e","i","o","u"]
any ideas how to check for e i o u at the same time?
If you do not need to know which vowels are present, you can use any as follows.
vowels = ("a", "e", "i", "o", "u")
word = input("type a word: ")
if any(v in word for v in vowels):
print("There is at least one vowel in your word.")
else:
print("There is no vowel in your word.")
One way to keep track is also to have an existence list that keeps all vowels that exist in a word.
existence = []
vowels = ["a","e","i","o","u"]
test_word = "hello" # You can change this to receive input from user
for char in test_word:
if char in vowels:
existence.append(char)
if existence and len(existence) > 0:
for char in existence:
print(f"These vowels exist in your input {test_word} - {char}")
else:
print(f"There are no vowels existing in your input {test_word}")
Output:
These vowels exist in your input hello - e
These vowels exist in your input hello - o
A regular expression can tell you not only if there's a vowel in a string, but which vowels and their order.
>>> import re
>>> re.findall('[aeiou]', 'hello')
['e', 'o']
I feel that if you want to use only if statements, then you can only choose one of the vowels but if you wish to use the for and if statements, it can go through with the whole vowels
I can solve your problem.
Here is the code:
vowels = {'a','e','i','o','u'}
word = input("Enter a word: ")
for vowel in word:
if vowel in vowels:
print(vowel,"is a vowel")
you have to iterate over the list.
vowels = ["a","e","i","o","u"]
word = input("type a word: ")
for vowel in vowels:
if vowel in word:
print (f"There is the vowel {vowel} in your word")
else:
print ("There is no vowel in your word")
iteration is the proces where you go through each item in a list.
for example.
list_a = ['a', 'b', 'c' ]
for item in list_a:
print(item)
#output will be a b c
since other user complained in a comment. If you want to stop the loop after vowel found, you should add break statment
vowels = ["a","e","i","o","u"]
word = input("type a word: ")
for vowel in vowels:
if vowel in word:
print (f"There is the vowel {vowel} in your word")
break
else:
print ("There is no vowel in your word")
I am writing a python code that takes a single imputed line of text and adds the string "tak" before every vowel (y only counting as a vowel if it doesn't begin a word) for example "I like sleep" would come out to "takI ltakitake sltaketakep". I am only just beginning learning to code and as such do not know too many complex functions yet. Below is the code I have thus far, which isn't working at all.
text = raw_input("enter the text to be translated")
textSplit = text.split()
count = 0
print len(textSplit)
Vowels = ["a","e","i","o","u"]
while count <= len(text):
for i in textSplit:
for i in Vowels:
count += 1
However, I have not been able to figure out how I can slice the string, add "tak" and concatenate it.
Thank you.
edit: can it be done without using the text.replace module?
You can use a regex:
>>> re.sub(r'(?i)([aeiou])', r'tak\1', "I like sleep")
'takI ltakiktake sltaketakep'
You can also use str.replace by looping over the string once for each vowel. Don't forget that strings are immutable in Python so you have to create a new string each time:
>>> s="I like sleep"
>>> for v in 'aeiouAEIOU':
... s=s.replace(v, 'tak'+v)
...
>>> s
'takI ltakiktake sltaketakep'
In this case, the string s is either the same as before if the vowel is not found or each vowel is replaced by the string tak concatenated to the vowel. A new string is created in either case each time through the loop and assigned to s.
You could use re.sub:
re.sub(r'([aeiou])', r'(exampleReplace)\1', text)
Example:
text = 'Text'
print(re.sub(r'([aeiou])', r'(exampleReplace)\1', text))
>> T(exampleReplace)ext
If you need to ignore any leading 'y's, you'll have to finesse it just a bit:
text = raw_input("enter the text to be translated")
temp1 = temp2 = text[1:] if text[0] in ['y', 'Y'] else text
for vowel in ['a', 'e', 'i', 'o', 'u', 'y']:
temp2 = temp2.replace(vowel, 'tak{}'.format(vowel))
temp2 = temp2.replace(vowel.upper(), 'tak{}'.format(vowel.upper()))
text = text.replace(temp1, temp2)
print text
For an input of 'I like sleep', this gives:
takI ltakiktake sltaketakep
'yellow':
ytakelltakow
'turkey':
ttakurktaketaky
If, for some reason, you really didn't want to use str.replace, you could do it like this:
text = raw_input("enter the text to be translated")
temp2 = text[1:] if text[0] in ['y', 'Y'] else text
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
temp2 = ''.join(['tak{}'.format(letter) if letter.lower() in vowels else letter for letter in temp2])
if text[0] in ['y', 'Y']:
text = text[0] + temp2
else:
text = temp2
print text
Use list() instead of split(). I have also used enumerate to get the index and value simultaneously.
Modified code:
text = "I like banana"
textSplit = list(text)
Vowels = ["a","e","i","o","u"]
for index,letter in enumerate(textSplit):
if letter.lower() in Vowels:
textSplit[index] = "tak" + letter
print "".join(textSplit)
Output:
takI ltakiktake btakantakantaka
The following would work:
text = 'I like sleep'
vowels = set("aeiou")
modified_text = ''.join(['tak'+letter if letter.lower() in vowels else letter for letter in text])
print(modified_text)
Output
takI ltakiktake sltaketakep
(note: I think you are missing a k in your sample output)
I'm a bit confused as to why this is not working. I'm writing a simple nested for-loop statement to replace vowels in a String but I'm not getting the expected output.
Using Python 3.5
#Excersise to remove vowels in a String
vowels = ['a','e','i','o','u']
user_in = input("Please enter a string: ")
user_in = user_in.lower()
for c in user_in:
for vowel in vowels:
if vowel == c:
new_string = user_in.replace(c, "")
print (new_string)
Input: "This is a string"
Output: "Ths s a strng
Wondering why the 'a' is still there?
Thanks!
The common way to do this is:
accum = ""
for c in user_in:
if c not in vowels: # note the reversed logic
accum += c
Or with a list comprehension and str.join
''.join([c for c in user_in if c not in vowels])
The ultimate problem is that every time you remove a vowel, you assign it to a different string, which is then discarded on the next iteration. The simple fix of doing user_in = user_in.replace(c, '') doesn't work because then you're changing the length of the string, which wreaks havoc when you're iterating over it. You could do
for c in user_in[:]:
if c in vowels:
user_in = user_in.replace(c, '')
Because the slice [:] is shorthand for creating a new copy of user_in that isn't affected by the replacements, while still letting you operate on a persistent version of user_in
As noted in the comments, due to how you are checking for vowels in the string, only the last vowels is replaced. Give this a try instead:
vowels = ['a','e','i','o','u']
user_in = input("Please enter a string: ")
user_in = user_in.lower()
new_string = “”
for c in user_in:
if(c not in vowels):
new_string += str(c)
print (new_string)
This code checks each character in the user input (user_in) and adds each character to the output string (new_string) if it is not in the list of vowels.
The join() method seemed to do the trick. Not sure if it's the most algorithmically efficient but it's passing all tests.
Solution:
#Excersise to remove vowels in a String
vowels = ['a','e','i','o','u']
user_in = input("Please enter a string: ")
user_in = user_in.lower()
new_string = []
for c in user_in:
if c not in vowels:
new_string.append(c)
new_string = ''.join(new_string)
print (new_string)
Thanks guys!!!!!
More efficient answer:
#Excersise to remove vowels in a String
vowels = ['a','e','i','o','u']
user_in = input("Please enter a string: ")
user_in = user_in.lower()
user_out = ""
for char in user_in:
if char not in vowels:
user_out += char
print (user_out)
I Am writing a function that should take a string input and return the string with every first letter of every word as a capital letter, I have achieved this to a certain degree.
My Code:
string = input("Please Enter A string:")
def capitalize_words(string):
split = string.split()
letter1 = ''
letter2 = ''
letter3 = ''
str1 = split[0]
str2 = split[1]
str3 = split[2]
for i in str1:
if i in str1[0]:
first = i.upper()
else:
letter1 = letter1 + i
string1 = (first+letter1)
for i in str2:
if i in str2[0]:
first = i.upper()
else:
letter2 = letter2 + i
string2 = (first+letter2)
for i in str3:
if i in str3[0]:
first = i.upper()
else:
letter3 = letter3 + i
string3 = (first+letter3)
result = string1+' '+string2+' '+string3
return result
func = capitalize_words(string)
print(func)
Input:
Please Enter A string:herp derp sherp
Output:
Herp Derp Sherp
However this is very inflexible because i can only enter 3 words with spaces no more no less , this makes for a rather primal program. I would like to be able to enter anything and get the desired result of the first letter of every word being a capital letter no matter how many words i enter.
I fear with my skills this is as far as I am able to get, can you please improve my program if possible.
>>> print(raw_input('Please Enter A string: ').title())
Please Enter A string: herp derp sherp
Herp Derp Sherp
Use str.title() to achieve what you want in one go.
But to process words in a sentence, use a loop instead of a series of local variables; here is a version that does the same what you are doing for an arbitrary number of words:
for i, word in enumerate(split):
split[i] = word[0].upper() + word[1:]
result = ' '.join(split)
I used string slicing as well to select just the first character, and all but the first character of a word. Note the use of enumerate() to give us a counter which wich we can replace words in the split list directly.
An alternative method is to use re.sub such as:
re.sub(r'\b.', lambda c: c.group().upper(), 'herp derp sherp and co.')
# 'Herp Derp Sherp And Co.'
You could write this in a one-line generator expression:
def upper_case(text):
return ' '.join(w[0].upper() + w[1:] for w in text.split())
Notice, that this function fails on single letter words and replaces any whitespace by a single space character.
Use this as
In [1]: upper_case(input('Please Enter A string: '))
Please Enter A string: hello world
Out[1]: 'Hello World'
I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So for instance:
#here is a variable containing a word:
my_word = "Acrobat"
#letters in vowel as a list
the_vowel = ["a","e","i","o","u"]
How do a check that the first letter in "Acrobat" is one of the vowels in the list? I also need to take into consideration whether it is upper or lowercase?
try my_word[0].lower() in the_vowel
I don't know if it is better than the answers already posted here, but you could also do:
vowels = ('a','e','i','o','u','A','E','I','O','U')
myWord.startswith(vowels)
Here are some hints to help you figure it out.
To get a single letter from a string subscript the string.
>>> 'abcd'[2]
'c'
Note that the first character is character zero, the second character is character one, and so forth.
The next thing to note is that an upper case letter does not compare equal to a lower case letter:
>>> 'a' == 'A'
False
Luckily, python strings have the methods upper and lower to change the case of a string:
>>> 'abc'.upper()
'ABC'
>>> 'a' == 'A'.lower()
True
To test for membership in a list us in:
>>> 3 in [1, 2, 3]
True
>>> 8 in [1, 2, 3]
False
So in order to solve your problem, tie together subscripting to get a single letter, upper/lower to adjust case, and testing for membership using in.
my_word = "Acrobat"
the_vowel = "aeiou"
if myword[0].lower() in the_vowel:
print('1st letter is a vowel')
else:
print('Not vowel')
My code looks like this.
original = raw_input("Enter a word:")
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print word
print first
print "vowel!"
else:
print word
print first
print "consonant
x = (input ("Enter any word: "))
vowel = "aeiouAEIOU"
if x[0] in vowel:
print ("1st letter is vowel: ",x)
else:
print ("1st letter is consonant: ",x)
Here's how I did it since the inputted word needs to be checked first before storing it as a variable:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
else:
print 'empty'
changes:
if my_word[0] in ('a','e','i','o','u'):
print(' Yes, the first letter is vowel ')
else:
print(' No, the first letter is not vowel ')
So, Here is the simple code for finding out that the first letter is either vowel or not!! If you have any further query in python or js, then comment it down.
import ast,sys
input_str = sys.stdin.read()
if input_str[0] in ['a','e','i','o','u','A','E','I','O','U']:
print('YES')
else:
print('NO')
Here is the solution to the exercise on codecadmy.com:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print 'vowel'
else:
print 'consonant'
else:
print 'empty'
Will it not be (slightly) faster to define the_vowel as a dictionary than a list?
the_vowel = {"a":1,"e":1,"i":1,"o":1,"u":1}
my_word[0].lower() in the_vowel
anti vowel Function
def anti_vowel(text):
vowel = ["a","e","i","o","u"]
new_text = ''
for char in text:
if char.lower() in vowel:
continue
else:
new_text += char
print new_text
return new_text
x = raw_input("Enter a word: ")
vowels=['a','e','i','o','u']
for vowel in vowels:
if vowel in x:
print "Vowels"
else:
print "No vowels"
This would print out 5 lines, if any of those includes a line that says Vowels then that means there is a vowel. I know this isn't the best way but it works.
Let's do it in more simply way
def check_vowel(s1):
v=['a','e','i','o','u']
for i in v:
if s1[0].lower()==i:
return (f'{s1} start with Vowel word {i}')
else:
return (f" {s1} start with Consonants word {s1[0]}")
print(check_vowel("orange"))
inp = input('Enter a name to check if it starts with vowel : ') *# Here we ask for a word*
vowel = ['A','E','I','O','U', 'a','e','i','o','u'] *# This is the list of all vowels*
if inp[0] in vowel:
print('YES') *# Here with the if statement we check if the first alphabet is a vowel (alphabet from the list vowel)*
else:
print('NO') *# Here we get the response as NO if the first alphabet is not a vowel*
my_word = "Acrobat"
the_vowel = ["a", "e", "i", "o", "u"]
if my_word[0].lower() in the_vowel:
print(my_word + " starts with a vowel")
else:
print(my_word + " doesnt start with a vowel")
input_str="aeroplane"
if input_str[0].lower() in ['a','e','i','o','u']:
print('YES')
else:
print('NO')
Output will be YES as the input string starts with a here.