pythonstrip

How do I input multiple arguments into strip() function?


today I was tasked to create a program that takes a user input and prints out the vowels and constants of what the user input was. I thought I was doing good so far but then I got an error while trying to use strip(). The error said the max arguments it could take were 1 and I was putting in multiple. How should I go about this?

lst1 = ['a','e','i','o','u']

lst2 = ['b','c','d','f','g','j','k','l','m','n','p','q','s','t','v','x','z','h','r','w','y']

lst3 = [] ### this is for vowels

lst4 = [] ### this is for userinput

lst5 = [] ### this is for constants

def vowelstrip(lst4):
    



maxlength = 1
while len(lst4) < maxlength:
    lst4 = input('Enter a line of text: ')
    lst3 = lst4.strip('b','c','d','f','g','j','k','l','m','n','p','q','s','t','v','x','z','h','r','w','y')
    lst5 = lst4.strip('a','e','i','o','u')
    print(f'vowels are: {lst3}\n Constants are: {lst5}')


Solution

  • You can have strip remove multiple characters by specifying them as a single string (not multiple arguments), but it only removes characters from the beginning and end of a string, not the middle, so it's not really suitable for what you're trying to do:

    >>> "foobar".strip("rf")
    'ooba'
    >>> "foobar".strip("aeiou")
    'foobar'
    

    I'd suggest using a generator expression and join to build a new string by iterating over the user's input:

    vowels = 'aeiou'
    
    
    def extract_vowels(text: str) -> str:
        return ''.join(c for c in text if c in vowels)
    
    
    def extract_consonants(text: str) -> str:
        return ''.join(c for c in text if c.isalpha() and c not in vowels)
    
    
    text = input('Enter a line of text: ')
    print(f'vowels are: {extract_vowels(text)}')
    print(f'consonants are: {extract_consonants(text)}')
    
    Enter a line of text: the quick brown fox
    vowels are: euioo
    consonants are: thqckbrwnfx