Python3无法连接错误?怎么修?

时间:2017-03-28 01:27:04

标签: function python-3.x join concatenation

鉴于我构建的这个函数,我收到最后一个return语句的错误,说我不能将它们连接在一起。还有其他方法可以做到这一点吗?

def simple_pig_latin(input, sep=' ', end='.'):
words=input.split(sep)
Vowels= ('a','e','i','o','u')
Digit= (0,1,2,3,4,5,6,7,8,9)
cons=('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z')
characters= ('!','@','#','$','%','^','&','*','.')
new_sentence=[]

for word in words:
    if word:
        if word[0]==" ":
            new_word=word   
        else:
            if word[0] in Vowels:
                new_word= word+"way"

            elif word[0] in Digit:
                new_word= word

            elif word[0] in cons:
                first_letter=word[0] #saves the first letter
                change= str(word) #change to string                     
                rem= change.replace(first_letter,'')#remove the first letter
                put_last= rem+first_letter #add letter to end
                new_word= put_last+ "ay"

            elif word[0] in characters:
                new_word= word

            new_sentence= new_sentence + new_word+ sep
    else:
        new_sentence.append(word)

return sep.join(new_sentence)+end

1 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西。 (你需要使用''.join())

def simple_pig_latin(input, sep=' ', end='.'):
    words=input.split(sep)
    Vowels= ('a','e','i','o','u')
    Digit= (0,1,2,3,4,5,6,7,8,9)
    cons=('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z')
    characters= ('!','@','#','$','%','^','&','*','.')
    new_sentence=[]
    for word in words:
        if word:
            if word[0]==" ":
                new_word=word
            else:
                if word[0] in Vowels:
                    new_word= word+"way"
                elif word[0] in Digit:
                    new_word= word
                elif word[0] in cons:
                    first_letter=word[0] #saves the first letter
                    change= str(word) #change to string
                    rem= change.replace(first_letter,'')#remove the first letter
                    put_last= rem+first_letter #add letter to end
                    new_word= put_last+ "ay"
                elif word[0] in characters:
                    new_word= word
                new_sentence= ''.join(new_sentence) + ''.join(new_word) + ''.join(sep)
        else:
            new_sentence.append(word)

    "".join(new_sentence)
    return new_sentence




    print simple_pig_latin("welcome to the jungle.")  # Sample call to func

结果

    lcomeway otay hetay ungle.jay

编辑1

替代方式

def simple_pig_latin(input, sep=' ', end='.'):
    words = input.split(sep)
    sentence =""
    for word in words:
        endString= str(word[1:])
        them=endString, str(word[0:1]), 'ay'
        newWords="".join(them)
        sentence = sentence + sep + newWords
    sentence = sentence + end
    return sentence


    print simple_pig_latin("I like this ")