错误“‘type’类型的对象没有 len()”

sam*_*tha 0 python typeerror

vowlist=['a','e','i','o','u']
def piglatin(s):
    if len(s)==1:
        if s[0] in vowlist:
            return s[0]+'way'
        else:
            return s[0]+'ay'
    elif s[0]==' '*len(s):
        return ' '
    elif len(s)>1:
        if s[0] in vowlist or (s[0]=='y' and s[1] not in vowlist):
            return s[0:]+'way'
        else:
            return new(s)
def new(s):
    global str
    if s[0] not in vowlist:
        str=s[0]+new(s[1:])
    else:
        return s[len(str):]+str[0:]+'ay'
print piglatin('school')
print piglatin('yttribium')
print piglatin('yolo') 
Run Code Online (Sandbox Code Playgroud)

这是我写的代码。它应该输出:

oolschay
yttribiumway
oloyay
Run Code Online (Sandbox Code Playgroud)

但它给出了错误object of type 'type' has no len()这是为什么?

Asa*_*din 5

str是Python中的一种类型。为您的变量使用不同的标识符。改变这个方法:

def new(s):
    global str
    if s[0] not in vowlist:
        str=s[0]+new(s[1:])
    else:
        return s[len(str):]+str[0:]+'ay'
Run Code Online (Sandbox Code Playgroud)

对此:

def new(s):
    global my_str
    if s[0] not in vowlist:
        my_str=s[0]+new(s[1:])
    else:
        return s[len(my_str):]+my_str[0:]+'ay'
Run Code Online (Sandbox Code Playgroud)