Home > Enterprise >  Python- How to strip a sting for more than one character with user inputs
Python- How to strip a sting for more than one character with user inputs

Time:12-29

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)

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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)
  • Related