Why is my function partially doing what it’s supposed to do? - python

So I’m trying to write a Python 3 function for a challenge that takes in a string, removes the vowels and returns it without the vowels. I wrote the below code but it seems to only take out the vowels partially while leaving some untouched.
def remove_vowels(string):
vowels = ['a','e','i','o','u']
newstring = ""
for letter in string:
if letter in vowels:
newstring = string.replace(letter,””)
else:
pass
return newstring

Your original python code with the following input
print(remove_vowels("The quick brown fox jumps over the lazy dog"))
returns "The quick brwn fx jumps ver the lazy dg"
The reason this only removes the "o" vowel is because your iterating through each vowel and updating your new string to the passed string minus the current vowel your on. So for example the first time through your for loop your "newstring" variable will be:
The quick brown fox jumps over the lzy dog
Then the next iteration your "newstring" variable will be set to
Th quick brown fox jumps ovr th lazy dog
And so on and so on. The reason my example only removes the o's is because there is no U to replace so the string replace method is never called leaving the "newstring" variables without o's.
To fix this you would just remove newstring completely and update the original string as this is it's own variable and this would technically work as is.
Although this can be compressed and refactored for better performance quite easily as you don't actually need to iterate through your string at all (nor do you need any type of new string as the passed string is it's own variable you are able to update) as pythons "String.replace" will replace ALL occurrences of the supplied substring and return the resulting string (if you don't supply a max amount of occurrences).
The following code below works
def remove_vowels(string):
vowels = 'aeiou'
for vowel in vowels: string = string.replace(vowel,'')
return string
print(remove_vowels("The quick brown fox jumps over the lazy dog"))
and returns "Th qck brwn fx jmps vr th lzy dg"

That's because you're setting newstring to a different string output on every iteration of the loop newstring = string.replace("")
You need to set newstring to the replaced string, and then run the next iteration of replace on newstring. Like this:
def remove_vowels(string):
vowels = ['a','e','i','o','u']
newstring = string
for letter in newstring:
if letter in vowels:
newstring = newstring.replace(letter , "")
return newstring
string = "stack overflow"
print("Original string = ", string)
print("String with vowels removed = ", remove_vowels(string))
Output:
Original string = stack overflow
String with vowels removed = stck vrflw

An alternative, short solution with a list comprehension:
def remove_vowels(string):
not_vowels = [letter for letter in string if letter not in 'aeiou']
return ''.join(not_vowels)

Make the following modifications to your code and it should work like a charm :)
def remove_vowels(string):
vowels = 'aeiou'
for letter in string:
if letter in vowels:
string = string.replace(letter," ")
else:
pass
return string

You are replacing a character in original string each time, but the original string never changes with current logic (except in the last loop).
try this inside IF condition
newstring = newstring.replace(letter,"")
(also initialize newstring = string before for loop)

Your code has several defects:
You are updating new_string with string, which does not change, and that results in only the last vowel in the list is deleted.
You do not need else: pass, it's ok with only the if clause. The else: pass is redundant.
You are cycling through the letters in string, which is not the fastest way to do things, also, it will create all kinds of weird errors if your code is changing string. You can knock outfor i in new_string:if i in vowels with for i in vowels
The vowels does not have to be a list if you are only iterating over it.Try a tuple or a str for better efficiency.
The overall fix:
def remove_vowels(string):
vowels = ('a','e','i','o','u')
newstring = string
for letter in vowels:
newstring = newstring.replace(letter,””)
return newstring
or:
def remove_vowels(string):
vowels = ('a','e','i','o','u')
for letter in vowels:
string = string.replace(letter,””)
return string

Related

Python- How to strip a sting for more than one character with user inputs [duplicate]

This question already has answers here:
Best way to replace multiple characters in a string?
(16 answers)
Closed last month.
For homework, I have to design a program that accepts a string as user input.
Users must also input some characters (more than one) that want to remove from the orinal string:
user input = The quick brown fox jumps over the lazy dog.
characters to strip = a,e,i,o,u
result = Th qck brwn fx jmps vr th lzy dg.
I would appreciate any help. Please keep the code simple.
This exercise is about string handling.
I have covered loops and strings.
NO lists nor lists comprehensions nor Dictionaries nor functions.
I would appreciate if you could keep your code related to the topics I have covered.
Thank you
string = input('Please type something: ')
characters = input('What characters would you like to strip: ')
for char in string:
for j in characters:
new_string = string.replace(char, '')
print(new_string)
You don't need to iterate over the string, only over the characters to remove
string = 'The quick brown fox jumps over the lazy dog.'
characters = 'aeiou'
new_string = string
for char in characters:
new_string = new_string.replace(char, '')
print(new_string) # Th qck brwn fx jmps vr th lzy dg.
Explaination, you need to iterate through all the character in the string and for each individual character see if that character is in banned characters or not.
if present there then igonre any processing on that character otherwise, add that character to a list
once whole string is processed then, to make the list of character to string back again use str.join method
this is code
string = 'The quick brown fox jumps over the lazy dog.'
characters = set('aeiou')
# store the character which are not to removed
string_characters =[]
for char in string:
# checking if letter in string is present in character or not in O(1) time
if char not in characters:
string_characters.append(char)
new_string = ''.join(string_characters) # use join function to convert list of characters to a string
print(new_string)
Easier way to do this, No need to do with function.
_string = input("Please type something: ")
if _string == 'x':
exit()
else:
newstring = _string
print("\nRemoving vowels from the given string")
vowels = ('a', 'e', 'i', 'o', 'u')
for x in _string.lower():
if x in vowels:
newstring = newstring.replace(x,"")
print(newstring)
Result:
Th qck brwn fx jmps vr th lzy dg
Or Using oneliners:
_string = input("Enter any string: ")
remove_str = ''.join([x for x in _string if x.lower() not in 'aeiou'])
print(remove_str)

How to solve the string indices must be integers problem in a for loop for capitalizing every word in a string

I hope everyone is safe.
I am trying to go over a string and capitalize every first letter of the string.
I know I can use .title() but
a) I want to figure out how to use capitalize or something else in this case - basics, and
b) The strings in the tests, have some words with (') which makes .title() confused and capitalize the letter after the (').
def to_jaden_case(string):
appended_string = ''
word = len(string.split())
for word in string:
new_word = string[word].capitalize()
appended_string +=str(new_word)
return appended_string
The problem is the interpreter gives me "TypeError: string indices must be integers" even tho I have an integer input in 'word'. Any help?
thanks!
You are doing some strange things in the code.
First, you split the string just to count the number of words, but don't store it to manipulate the words after that.
Second, when iterating a string with a for in, what you get are the characters of the string, not the words.
I have made a small snippet to help you do what you desire:
def first_letter_of_word_upper(string, exclusions=["a", "the"]):
words = string.split()
for i, w in enumerate(words):
if w not in exclusions:
words[i] = w[0].upper() + w[1:]
return " ".join(words)
test = first_letter_of_word_upper("miguel angelo santos bicudo")
test2 = first_letter_of_word_upper("doing a bunch of things", ["a", "of"])
print(test)
print(test2)
Notes:
I assigned the value of the string splitting to a variable to use it in the loop
As a bonus, I included a list to allow you exclude words that you don't want to capitalize.
I use the original same array of split words to build the result... and then join based on that array. This a way to do it efficiently.
Also, I show some useful Python tricks... first is enumerate(iterable) that returns tuples (i, j) where i is the positional index, and j is the value at that position. Second, I use w[1:] to get a substring of the current word that starts at character index 1 and goes all the way to the end of the string. Ah, and also the usage of optional parameters in the list of arguments of the function... really useful things to learn! If you didn't know them already. =)
You have a logical error in your code:
You have used word = len(string.split()) which is of no use ,Also there is an issue in the for loop logic.
Try this below :
def to_jaden_case(string):
appended_string = ''
word_list = string.split()
for i in range(len(word_list)):
new_word = word_list[i].capitalize()
appended_string += str(new_word) + " "
return appended_string
from re import findall
def capitalize_words(string):
words = findall(r'\w+[\']*\w+', string)
for word in words:
string = string.replace(word, word.capitalize())
return string
This just grabs all the words in the string, then replaces the words in the original string, the characters inside the [ ] will be included in the word aswell
You are using string index to access another string word is a string you are accessing word using string[word] this causing the error.
def to_jaden_case(string):
appended_string = ''
for word in string.split():
new_word = word.capitalize()
appended_string += new_word
return appended_string
Simple solution using map()
def to_jaden_case(string):
return ' '.join(map(str.capitalize, string.split()))
In for word in string: word will iterate over the characters in string. What you want to do is something like this:
def to_jaden_case(string):
appended_string = ''
splitted_string = string.split()
for word in splitted_string:
new_word = word.capitalize()
appended_string += new_word
return appended_string
The output for to_jaden_case("abc def ghi") is now "AbcDefGhi", this is CammelCase. I suppose you actually want this: "Abc Def Ghi". To achieve that, you must do:
def to_jaden_case(string):
appended_string = ''
splitted_string = string.split()
for word in splitted_string:
new_word = word.capitalize()
appended_string += new_word + " "
return appended_string[:-1] # removes the last space.
Look, in your code word is a character of string, it is not index, therefore you can't use string[word], you can correct this problem by modifying your loop or using word instead of string[word]
So your rectified code will be:
def to_jaden_case(string):
appended_string = ''
for word in range(len(string)):
new_word = string[word].capitalize()
appended_string +=str(new_word)
return appended_string
Here I Changed The Third Line for word in string with for word in len(string), the counterpart give you index of each character and you can use them!
Also I removed the split line, because it's unnecessary and you can do it on for loop like len(string)

python - replace string with condition yields weird result

I wrote a function that replace the letter if the letter is the same as the next letter in the string:
word = 'abcdeefghiijkl'
def replace_letter(word):
for i in range(len(word)-1):
if word[i] == word[i+1]:
word = word.replace(word[i],'7')
return word
replace_letter(word)
This should give me 'abcd7efgh7ijkl', but I got 'abcd77fgh77jkl'. Once the letter is the same with the next one both are replaced with '7'.
Why?
You should use:
word = word.replace(word[i],'7', 1)
to indicate that you want to make one character replacement. Calling replace() without indicating how many replacements you wish to make will replace any occurrence of the character "e" (as found at word[i]) by "7".
the answer above has a little bug
for example:
when your word = 'ebcdeefghiijkl'
the result of replace_letter(word) will be '7abcdeefgh7ijkl'
you can try this:
def replace_letter(word):
result=[]
for i in range(len(word)):
if i!=len(word)-1 and word[i] == word[i+1]:
result.append('7')
else:
result.append(word[i])
return ''.join(result)

Python: How to print results from conditions all in one line [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))

Python: Pig Latin Function

I'm stuck on a really hard question for my class in which I need to create a Pig Latin converter in Python for a given string.
Basically, here are the rules.
For any word that begins with one or more consonants (y is considered a consonant):
move the consonants to the end of the word and append the string 'ay'.
For all other words, append the string 'way' to the end.
The function also must be case deal with punctuation and case sensitivity, it is suggested that we create a separate function to find the initial vowel of any word and use it in the main function, which I kinda did, however, I'm having trouble implementing the Case and punctuation into my main formula and what to do if a word has no vowels (since "y" doesn't count as a vowel in our case, the word "my" doesn't have a vowel.
Here's my code so far.
def vowelfinder(astring):
vowels = ["A","E","I","O","U","a","e","i","o","u"]
alist = astring.split()
for i in alist:
for j in range(len(i)):
if i[j] in vowels:
print(j)
break
def igpay(astring):
vowelfinder(astring)
for i in alist
Any advice is helpful
# For any word that begins with one or more consonants (y is considered a consonant):
if "aeiouAEIOU".find(astring[0]) == -1:
# move the consonants to the end of the word and append the string 'ay'.
return astring[1:] + astring[0] + "ay"
# For all other words,
else:
# append the string 'way' to the end.
return astring + "way"
This is for a word. Splitting into words should be easy enough.
EDIT: brainfart.

Categories

Resources