Python -- List traversal - python

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)

Related

How do i combine these print statements?

word = input("Translate a word: ")
for char in word:
if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz":
print(char + "o" + char)
else:
print(char)
I have this code for a translator to a language where you add an "o" after each consonant followed by that same consonant again. When i run it and type in for example "stair" it would print out:
sos
tot
a
i
ror
If someone has an idea on how to print this out on the same line without spacing i would be very grateful!
Don't print each time but append the result to a string and print the final string:
word = input("Translate a word: ")
result = ''
for char in word:
if char not in "aeiouyAEIOUY":
result+=char + "o" + char
else:
result+=char
print(result)
One option is to use list comprehension to create a list with your values:
[char+'o'+char if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" else char for char in word]
and then if you need to smash them together into a string you just use a join()
''.join([char+'o'+char if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" else char for char in word])
Add records to a list and use print function with * to print records in the same line.
word = input("Translate a word: ")
data = [] #create a empty list
for char in word:
if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz":
data.append(char + "o" + char) #add elements to list
else:
data.append(char) #add elements to list
print(*data, sep='') #print list elements in single line without spaces
If you want to use the print statement as you are currently doing, just try below option of print statement which defines the ending of the print statement.
word = input("Translate a word: ")
for char in word:
if char in "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz":
print(char + "o" + char,end="")
else:
print(char,end="")
The output of the above code on input "stair" will be "sostotairor". Hope it helps!
You can double the consonants in a list first and join the characters with o:
word = input("Translate a word: ")
for char in word.lower():
print('o'.join([char] * ((char not in 'aeiou') + 1)))
Sample input/output:
Translate a word: stair
sos
tot
a
i
ror

Editing a String without Python Commands (with "for i in range")

For an assignment, I need code that asks the user for a word and a letter. Then, it edits the word to not include the specific letter. It needs in include a "for i in range" statement. The code before works but doesn't use a for loop and uses a python command.
word1 = raw_input ("Give me a word! ")
letter1 = raw_input ("Give me a letter! ")
modify = word1.replace(letter1,"")
check = word1.find(letter1)
if check == -1:
print "There is no letters to replace in", word1
check = 0
if check >= 1:
print modify
How about:
word = raw_input('Give me a word! ')
letter = raw_input('Give me a letter! ')
cleaned = ''
for i in range(len(word)):
if word[i] != letter:
cleaned += word[i]
if cleaned:
print cleaned
else:
print 'There is no letters to replace in', word
You can iterate through a string letter by letter like you would a list or dict
word='someword'
for letter in word:
print(letter)

How do I convert all the vowels within a string to white-spaces in python

I am trying to take an input string and replace any vowels in it with a whitespace. How do you do this?
def w_space (s):
vowels = "aeiouAEIOU"
string = s
for a in string:
for b in vowels:
if string[a] == vowels[b]:
vowels = ""
return string
First of all instead of setting string = s simply loop through s as it is. Also, instead of looping through both s and vowels just loop s and check if the letter is in vowels, if so add a white space to string if not add the letter to string. Here is the code:
def w_space (s):
vowels = "aeiouAEIOU"
string = ""
for a in s:
if a in vowels:
string += " "
else:
string += a
return string
def f(s):
l = list(s)
for i in range(len(l)):
if l[i] in "aeiouAEIOU":
l[i] = " "
return ''.join(l)
This can be accomplished with a list comprehension
def w_space(s):
vowels = "aeiouAEIOU"
return "".join([" " if x in vowels else x for x in s])
Regex is an option as well
def w_space (s):
from re import sub, IGNORECASE
vowels = r'[aeiou]'
return sub(vowels, ' ', s, flags=IGNORECASE)

Capitalized Word Function

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'

checking if the first letter of a word is a vowel

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.

Categories