首页 > 解决方案 > 我正在尝试驼峰式四个短语

问题描述

超级初学者到Python这里。到目前为止,这是我的代码:

def make_camel_case(word_string):
    word_list = word_string.split(’ ’)
    output = ’’
    for word in word_list:
        word_upper = word[0].upper()
        output = output+word_upper
    return(output)
def camel_case():
    phrase1 = ’purple people eater’
    phrase2 = ’i can\’t believe it\’s not butter’
    phrase3 = ’heinz 57 sauce’
    print(make_camel_case(phrase1))
    print(make_camel_case(phrase2))
    print(make_camel_case(phrase3))
camel_case()

这是我想要的输出:

purplePeopleEater
iCan’tBelieveIt’sNotButter
heinz57Sauce

我的主要错误信息是invalid character in identifier in line 2

编辑后我的代码运行正常,但输出:

 PPE
 ICBINB
 H5S

标签: pythoncamelcasing

解决方案


很简单,只需使用capitalize()函数:

def make_camel_case(word_string):
    word_list = word_string.split(' ')
    output = ''

    for word in word_list:
        word_upper = word.capitalize()
        output += word_upper
    return output
def camel_case():
    phrase1 = 'purple people eater'
    phrase2 = "i can't believe it’s not butter"
    phrase3 = 'heinz 57 sauce'
    print(make_camel_case(phrase1))
    print(make_camel_case(phrase2))
    print(make_camel_case(phrase3))
camel_case()

推荐阅读