A single line with the inputs assembled in Camel Case

Viewed 1381

I'm trying to reformat a series of strings into Camel Case by returning the fragments from input as a single "sentence".

this is what I have so far -

def convert(s):
    if(len(s) == 0):
        return
    s1 = ''
    s1 += s[0].upper()
    for i in range(1, len(s)):
    if (s[i] == ' '):
        s1 += s[i + 1].upper()
        i += 1
    elif(s[i - 1] != ' '):
        s1 += s[i]
print(s1)    
         

# Driver Code
def main():
s = "BusOneBusTWOBUSthree"
convert(s)
 
if __name__=="__main__":
    main()

output I'm getting is - Bus One Bus TWO BUS three

output I'm wanting to get is -

busOne busTwo busThree

1 Answers

It looks like your example s= won't get you the output you say you're getting, so I am guessing that your input is space separated. It looks like you want to alternatively join 2 words together and make the 2nd word's first letter Uppercase. If so, split the string into a list, then iterate through the list and add to your final string. Here's one way to do that:

original_string = 'buS one buS two bus thRee'
original_string = original_string.lower()
list_of_words = original_string.split()     
# splits on space by default, or specify 'x' to split on the letter x

camel_case_output = ''
for i in range(len(list_of_words)):
    this_word = list_of_words[i]
    if i % 2 == 0:   # even numbers
        camel_case_output += list_of_words[i]
    else:
        this_word = this_word[0].upper() + this_word[1:]
        camel_case_output += this_word + ' '

camel_case_output.strip()       # remove the last space, if you ended with extra
Related