“方法”对象不可迭代

时间:2018-11-26 02:59:56

标签: python python-3.x

我正在编写代码,并试图将输入变量(YourName)重新分配为仅包含字母,并忽略任何数字(如果有意义)

while YourName == None:
    YourName = (input("But before we begin, what is your name?:")) #The name can be anything.
    YourName = YourName.capitalize()
    YourName = ''.join(filter(str.isalpha(YourName), input))

但是当我运行它时,它会产生“方法”不可迭代的问题。

我该如何解决

2 个答案:

答案 0 :(得分:0)

您可以使用re

import re

YourName = None

while YourName == None:
    YourName = (input("But before we begin, what is your name?:")) #The name  can be anything.
    YourName = YourName.capitalize()
    YourName = re.sub(r'\d+', '', YourName)
    print(YourName)

样本输出

But before we begin, what is your name?:ada64782jhadas
Adajhadas

答案 1 :(得分:0)

如果要使用过滤器,则该行应如下所示

YourName = ''.join(filter(str.isalpha, YourName))

完整程序

YourName = None

while YourName == None:
    YourName = (input("But before we begin, what is your name?:")) #The name  can be anything.
    YourName = YourName.capitalize()
    YourName = ''.join(filter(str.isalpha, YourName))
    print(YourName)

样本输出

But before we begin, what is your name?:1231af 45 sdfsd
afsdfsd

注意:您错过了空格

相关问题