Tuesday, January 21, 2020

Capitalize first character of a given string in Python and JavaScript

Lets take a look at how we can capitalize first character of a given string/phrase in both Python and JavaScript.

Assuming we have a string like this: 'bOY in LOVE' and we needed it transform properly to 'Boy in love'.


Python solution

In python, there is a built-in method to getting it done called capitalize().
So, all that is required is to call the capitalize() method on the string like this:

'bOY in LOVE'.capitalize()    



Lets assume, we are not aware the capitalize() method existed. Here is how we can construct one using the upper() and lower() methods.



def capitalize_fun(s):
    # checks if it is a string
    if type(s) is not str: 
        return ''
    else:
        return s[0].upper() + s[1:].lower()
    
capitalize_fun('bOY in LOVE')





JavaScript solution

Unlike python, JavaScript doesn't have a built-in method for doing this (at least as at the time of writing - 20/01/2020), so we have to use the concept above to write.

const capitalize = (s) => {
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase()
}

console.log(capitalize('bOY in LOVE'))





That is it!


No comments:

Post a Comment