Reputation: 59
Super beginner to Python
here. Here's my code so far:
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()
And here is my desired output:
purplePeopleEater
iCan’tBelieveIt’sNotButter
heinz57Sauce
My primary error message is invalid character in identifier in line 2
After an edit my code runs properly, but outputs:
PPE
ICBINB
H5S
Upvotes: 2
Views: 140
Reputation: 7685
Easy pease, just use the capitalize() function:
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()
Upvotes: 6
Reputation: 379
You are converting only the first character to upper case in word_upper
variable. To get the desired output you need to do 2 things.
enumerate()
to get the word index from loop (see here) and then for later words replace the first character only.
The code would bedef make_camel_case(word_string):
word_list = word_string.split(' ')
output = ''
for i,word in enumerate(word_list):
if(i != 0):
word_upper = word[0].upper()
word = word_upper + word[1:]
output = output + word
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()
For a cleaner solution, use str.capitalize()
function (see here) suggested by @federico-baù. Then the function would become something like this,
def make_camel_case(word_string):
word_list = word_string.split(' ')
output = ''
for i,word in enumerate(word_list):
if(i != 0):
word = word.capitalize()
output = output + word
return(output)
Hope it clarified your question. Keep learning.
Upvotes: 2
Reputation: 174
The error caused on second line is cause by causing indvalid character ’. You should use single quotes ' ' or double quotes " " to split text by spaces.
Then you can simply do .upper() for each first letter of each word to make it uppercase and at the end, merge all the words into the desired string.
Upvotes: 5