如何将多个参数输入到 strip() 函数中?

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

今天我的任务是创建一个程序,该程序接受用户输入并打印出用户输入的元音和常量。我认为到目前为止我做得很好,但后来我在尝试使用 strip() 时遇到错误。错误说它可以接受的最大参数是 1,而我输入了多个。我该怎么办?

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}')

您可以通过将多个字符指定为单个字符串(而不是多个参数)来让 strip 删除多个字符,但它只会删除字符串开头和结尾的字符,而不是中间的字符,所以它不是真的适合你想做的事:

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

我建议使用生成器表达式和 join 通过遍历用户输入来构建新字符串:

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