Home > Net >  Remove certain word from string
Remove certain word from string

Time:12-23

The program need to remove vowels from word. I tried something but don't know why it's not working.

Code:

n = input("Type word: ")
words = []
words.append(n)

while n != "":
    n = input("Type word: ")
    if n != "":
        words.append(n)
test = str(words)
print(test)
vowels = ("A", "B", "C", "D")
for i in test:
    if i in vowels:
        test.replace("A", "")
print(test)

CodePudding user response:

What you can do is simply iterate through every letter provided within the input, and check to see if it is within the list of vowels; if it is not, then add it to a separate string that will contain your cleaned message without any vowels.

VOWELS = ["a", "e", "i", "o", "u"] # Define a list of vowels.
message = input("Type word: ") # Get the input.
strippedMessage = "" # The separate variable to hold our parsed input.

for letter in message: # For every letter within the input.
    if letter.lower() not in VOWELS: # If the letter is not a vowel.
        strippedMessage  = letter # Add it to the stripped message.
print(strippedMessage)
Input: this is a sample message
Output: ths s  smpl mssg

CodePudding user response:

The replace method returns a copy of the modified string, it does not change the original string, you need to do that:

test = test.replace("A", "")

CodePudding user response:

Remove all vowels from a string using regex:

import re
str = input("Type word: ")
print(re.sub("[aeiou]", "", str, flags=re.IGNORECASE))

CodePudding user response:

You should change the while loop into a for loop or an if statement, otherwise it wouldn't end.

To replace the vowels you can use nested loops like this:

for i in test:
   for j in vowels:
      if j in i.upper():
          test = test.replace(i, "")
print(test)
  • Related