Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Letter Capitalize
    Hi, I had a tough time figuring out how to solve this simple challenge and finally managed to do it with the following code. Just wondering if there is a more efficient or proper way of doing it in Python. def LetterCapitalize(str): # code goes here str = str.split(" ") newword = [] l = len(str) for i in range(l): newword.append(str[i].capitalize()) newword = " ".join(newword) return newword print LetterCapitalize(raw_input())
    zohaan posted this question on 1/6/14 | python
    Answers
  • +
  • 11
  • -
  • you can learn amazing things by doing a little digging: return str.title()
  • +
  • 4
  • -
  • What about trying this way ? def LetterCapitalize(s): return (' ').join([x.capitalize() for x in s.split()]) print LetterCapitalize('james singh')
  • +
  • 1
  • -
  • the way i did it, was seek for a space " " followed by a letter. If found - caitalize. Also if the first char is a letter - capitalize. This is better, because if you have several spaces- you might loose them after splitting.
  • +
  • 1
  • -
  • why doesn't this work? function LetterCapitalize(str) { for (var i = 0; i < str.length; i++) { if (i = 0) { str.charAt(i).toUpperCase(); } else if (str[i] = " " && str[i+1] != " ") { str.charAt(i+1).toUpperCase(); } } // code goes here return str; }
  • +
  • 1
  • -
  • what means? newword = []
  • +
  • 0
  • -
  • @silentbogo, thanks i will try that one too...
  • +
  • 0
  • -
  • why doesn't this work? function LetterCapitalize(str) { for (var i = 0; i < str.length; i++) { if (i = 0) { str.charAt(i).toUpperCase(); } else if (str[i] = " " && str[i+1] != " ") { str.charAt(i+1).toUpperCase(); } } // code goes here return str; }
  • +
  • 0
  • -
  • @madcurie in elseif there is no arrayof string so instead try str.charAt(i) = " "
    Log in to write an answer.