Home > Net >  Python - Convert string to CamelCase
Python - Convert string to CamelCase

Time:09-04

I coded the following method to convert a string to Camel Case. However, it doesn't work when the string starts with a space.

def CamelCase(s):
 
  newString = ''
  newString  = s[0].upper()

  for k in range(1, len(s)): 
    if s[k] == ' ':
      newString  = s[k   1].upper()
      k  = 1
    elif s[k - 1] != ' ':
      newString  = s[k]
  return newString

The input is: " I love chocolate." And the output should be: "ILoveChocolate."

But it gives the following error:

    IndexError                                Traceback (most recent call last)
<ipython-input-13-28f7ddba2ba2> in <module>
----> 1 print(CamelCase("  Algoritmos y    estructuras de   datos   "))

<ipython-input-12-29aa8012fb61> in CamelCase(s)
      9     for k in range(1, len(s)):
     10       if s[k] == ' ':
---> 11         nuevaCadena  = s[k   1].upper()
     12         k  = 1
     13       elif s[k - 1] != ' ':

IndexError: string index out of range

Help?

CodePudding user response:

The string built-in function title() will help here:

def camelcase(s):
    return ''.join(t.title() for t in s.split())

Note that the first character in the returned string will be uppercase hence the value is upper camelcase (a.k.a. Pascal case) as opposed to the more common lower camelcase

CodePudding user response:

You are iterating k from 1 to the length of the string minus one. s[k 1] will therefore be out of bounds.

You'll want to do a few things:

  1. Use split to get a list of words. s.split()
  2. Use a generator expression to capitalize each string. re.sub(r'^[a-z]', lambda m: m.group(0).upper(), w) for w in s.split())
  3. Join this whole thing together into a string. ''.join(re.sub(r'^[a-z]', lambda m: m.group(0).upper(), w) for w in s.split())
>>> s = "  I love chocolate "
>>> ''.join(re.sub(r'^[a-z]', lambda m: m.group(0).upper(), w) for w in s.split())
'ILoveChocolate'

CodePudding user response:

You need to remove extra spaces using string.**strip()** method.

Here's how to do this on a pythonic way:

def convert_camel_case(string:str)->str:
    # strip before split the sentence
    return ''.join([word.capitalize() for word in string.strip().split()])

print(convert_camel_case("        I     love CHOCOLATE    ."))
python main.py
ILoveChocolate.

CodePudding user response:

I would go with conversion to list and back word by word and use a capitalize method. The closet syntax to the source example is:

def CamelCase(s):
 
    newString = ''
    
    for word in s.split(): 
      newString  = element.capitalize()
    return newString
  • Related