This question already has answers here:
Remove specific characters from a string
(2 answers)
Closed 8 years ago.
I'm trying to remove all the vowels from a string, using a function that is passed an argument called "text". I'm not sure if this is the most efficient way to code this, but it's all I could come up with. I'm not sure how to tell the function to check if "text" has any of the characters from the "vowels" list, and if so, to remove it. I thought replacing it with a space would do in the .replace() function would do the trick, but apparently not. The code is supposed to remove lower AND uppercase vowels, so I'm not sure if making them all lowercase is even acceptable. Thanks in advance.
def anti_vowel(text): #Function Definition
vowels = ['a','e','i','o','u'] #Letters to filter out
text = text.lower() #Convert string to lower case
for char in range(0,len(text)):
if char == vowels[0,4]:
text = text.replace(char,"")
else:
return text
Pretty simple using str.translate() (https://docs.python.org/2.7/library/stdtypes.html#str.translate)
return text.translate(None, 'aeiouAEIOU')
Python's Replace has you specify a substring to replace, not a position in the string. What you would want to do instead is
for char in range(0,5):
text = text.replace(vowels[char],"")
return text
UPDATED BASED ON COMMENT:
or you could do
for char in vowels:
text = text.replace(char,"");
return text;
Use the sub() function (https://docs.python.org/2/library/re.html#re.sub):
re.sub('[aeiou]', '', text)
Change your function to loop over the vowels list like this:
def anti_vowel(text): #Function Definition
vowels = ['a','e','i','o','u'] #Letters to filter out
text = text.lower() #Convert string to lower case
for vowel in vowels:
text = text.replace(vowel,"")
return text
This simply iterates over the vowels and replaces all occurrences of each vowel.
Related
I need to print a string, using this rules:
The first letter should be capital and make all other letters are lowercase. Only the characters a-z A-Z are allowed in the name, any other letters have to be deleted(spaces and tabs are not allowed and use underscores are used instead) and string could not be longer then 80 characters.
It seems to me that it is possible to do it somehow like this:
name = "hello2 sjsjs- skskskSkD"
string = name[0].upper() + name[1:].lower()
lenght = len(string) - 1
answer = ""
for letter in string:
x = letter.isalpha()
if x == False:
answer = string.replace(letter,"")
........
return answer
I think it's better to use a for loop or isalpha () here, but I can't think of a better way to do it. Can someone tell me how to do this?
For one-to-one and one-to-None mappings of characters, you can use the .translate() method of strings. The string module provides lists (strings) of the various types of characters including one for all letters in upper and lowercase (string.ascii_letters) but you could also use your own constant string such as 'abcdef....xyzABC...XYZ'.
import string
def cleanLetters(S):
nonLetters = S.translate(str.maketrans('','',' '+string.ascii_letters))
return S.translate(str.maketrans(' ','_',nonLetters))
Output:
cleanLetters("hello2 sjsjs- skskskSkD")
'hello_sjsjs_skskskSkD'
One method to accomplish this is to use regular expressions (regex) via the built-in re library. This enables the capturing of only the valid characters, and ignoring the rest.
Then, using basic string tools for the replacement and capitalisation, then a slice at the end.
For example:
import re
name = 'hello2 sjsjs- skskskSkD'
trans = str.maketrans({' ': '_', '\t': '_'})
''.join(re.findall('[a-zA-Z\s\t]', name)).translate(trans).capitalize()[:80]
>>> 'Hello_sjsjs_skskskskd'
Strings are immutable, so every time you do string.replace() it needs to iterate over the entire string to find characters to replace, and a new string is created. Instead of doing this, you could simply iterate over the current string and create a new list of characters that are valid. When you're done iterating over the string, use str.join() to join them all.
answer_l = []
for letter in string:
if letter == " " or letter == "\t":
answer_l.append("_") # Replace spaces or tabs with _
elif letter.isalpha():
answer_l.append(letter) # Use alphabet characters as-is
# else do nothing
answer = "".join(answer_l)
With string = 'hello2 sjsjs- skskskSkD', we have answer = 'hello_sjsjs_skskskSkD';
Now you could also write this using a generator expression instead of creating the entire list and then joining it. First, we define a function that returns the letter or "_" for our first two conditions, and an empty string for the else condition
def translate(letter):
if letter == " " or letter == "\t":
return "_"
elif letter.isalpha():
return letter
else:
return ""
Then,
answer = "".join(
translate(letter) for letter in string
)
To enforce the 80-character limit, just take answer[:80]. Because of the way slices work in python, this won't throw an error even when the length of answer is less than 80.
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 2 years ago.
I am learning python and in the course, I had to make a translator that transforms vowels into the letter "g".
In the program, I had to check if the phrase to be translated had any uppercase vowels in order to replace them with a capital letter "G".
And I fail to understand why .lower() doesn't apply for the rest of the code? In my thinking, if I apply letter.lower() in the next line the value of the variable letter should still be in lowercase. Here is my code:
def translate(phrase):
translated = ""
for letter in phrase:
if letter.lower() in "aeouiy":
if letter.isupper():
translated = translated + "G"
else:
translated = translated + "g"
else:
translated = translated + letter
return translated
print(translate(input("enter phrase to translate into giraffe elegant language: ")))
The strings in Python are immutable.
Strings are immutable sequences of Unicode code points.
And the lower() method of str class in Python doesn't modify the object in-place but it returns a new str object with all of it's characters lower cased.
Lower():
Return a copy of the string with all the cased characters converted to lowercase. For 8-bit strings, this method is locale-dependent.
See this too:
The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
You will need to reassign your str object to the one returned by lower() method. Like this:
letter = letter.lower()
.lower() is only applied for the line you are using it in. If you want to have it permanently, you have to assign it like this:
letter = letter.lower()
letter.lower() only applies for that line. You would need to change letter itself with letter = letter.lower().
No, letter.lower() returns a new, lower-cased letter. (In Python, strings are immutable.)
You'll need to reassign back to the name letter to get the behavior you want:
for letter in phrase:
letter = letter.lower()
if letter in "aeouiy":
...
or better yet, just lower-case all of phrase first:
phrase = phrase.lower()
for letter in phrase:
...
This question already has answers here:
python how to uppercase some characters in string
(9 answers)
Closed 4 years ago.
Thanks for your help
Example byron = bYrOn
This is an old homework I'm looking over.
It is actually preety simple to turn all letters in a string to upper case!
just use the variable name and follow .upper() at the end e.g.
byron="byron"
byron=byron.upper()
however, because you want to give only certain letters the "uppercase" status, you'd want to first assign all vowels:
vowels = set(['a','e','i','o','u'])
then use some python logic to do the rest:
for char in byron:
if char in vowels:
Word = Word.replace(char,(char.upper()))
print (Word)
if you want to be quick just copy the code below as it is the complete code used to do your task:
x="byron"
vowels = set(['a','e','i','o','u'])
Word=x
for char in Word:
if char in vowels:
Word = Word.replace(char,(char.upper()))
print(Word)
My code should recognize the vowel letters and remove them from input string using the replace() function. However it works fine except for the 'e' letter.
If the input is "Hey look Words!" the output is "Hey lk Wrds!".
It identifies the 'e' only if if the "vowels" string is equal to "e" or "eE" only!
I am curious to know why?
def anti_vowel(text):
vowles="AaEeOoIiUu"
newstr=""
for i in text:
if i in vowles:
newstr=text.replace(i,"")
return newstr
You are placing only the last replacement result in newstr. All your previous str.replace() results are discarded.
For your input text Hey look Words!, the last vowel encountered is o so only o is replaced. The e replacement did take place and was stored in newstr but that value was then discarded when you set newstr to the result of the o replacement. It thus depends on the input string what vowel exactly will remain replaced; for the sentence 'The cat sat on the mat' it'll be a as that is the last vowel you test and replace.
Just loop directly over vowels and replace each of those characters; it is save to call str.replace() where the first argument is not present. Store the result back in text so that any subsequent replacements stick:
def anti_vowel(text):
vowels = "AaEeOoIiUu"
for vowel in vowels:
text = text.replace(vowel, "")
return text
Better still, use the str.translate() method to replace all vowels in one go:
# Python 2 version
def anti_vowel(text):
vowels = "AaEeOoIiUu"
return text.translate(None, vowels)
# Python 3 version
def anti_vowel(text):
vowels = str.maketrans(dict.fromkeys("AaEeOoIiUu"))
return text.translate(vowels)
str.translate() makes all replacements at once; the method changed between Python 2 str and Python 3 str, but in both versions all the vowels are ignored as the new string is built, without any further loops.
There's no reason to iterate through all the letters in the word; the replace() method does that for you. And you are erasing newstr every time, so by the end, all you're doing is replacing u. Here's what you need to do.
def anti_vowel(text):
vowels = "AaEeIiOoUu"
for i in vowels:
text = text.replace(i, "")
return text
This way, each time you replace text, you save and keep the replaced string. What you were doing earlier was making newstr into text without A, then replacing newstr with text sans a (but with A), so on and so forth. The end result was text without u but with everything else.
You should change your code to:
def anti_vowel(text):
vowles="AaEeOoIiUu"
newstr=text
for i in newstr:
if i in vowles:
newstr=newstr.replace(i,"")
return newstr
Then you will acummulate each replacement in your final string.
The way you are doing you always use the original string and replace only one group of chars ('Ee', 'Aa', etc...) in each iteration. So, in the end, you get a result of only one of these groups replaced in the original string.
This question already has answers here:
def anti_vowel - codecademy (python)
(7 answers)
Closed 8 years ago.
What's wrong with this code? The aim is to check wether the entered string contains vowels and delete them
Here is the code:
def anti_vowel(text):
text = str(text)
vowel = "aeiouAEIOU"
for i in text:
for i in vowel.lower():
text = text.replace('i',' ')
for i in vowel.upper():
text = text.replace('i',' ')
return text
It's a lesson on Codecademy
You are trying to replace the string with the value 'i', not the contents of the variable i.
Your code is also very inefficient; you don't need to loop over every character in text; a loop over vowel is enough. Because you already include both upper and lowercase versions, the two loops over the lowercased and uppercased versions are in essence checking for each vowel 4 times.
The following would be enough:
def anti_vowel(text):
text = str(text)
vowel = "aeiouAEIOU"
for i in vowel:
text = text.replace(i,' ')
return text
You are also replacing vowels with spaces, not just deleting them.
The fastest way to delete (rather than replace) all vowels would be to use str.translate():
def anti_vowel(text):
return text.translate(text.maketrans('', '', 'aeiouAEIOU'))
The str.maketrans() static method produces a mapping that'll delete all characters named in the 3rd argument.