HackerRank Solution: Python Capitalize! [4 Methods]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Question: Capitalize! [Python Strings]

You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalized correctly as Alison Heck.

alishonheck ==> AlishonHeck

Given a full name, your task is to capitalize the name appropriately.

Input Format

A single line of input containing the full name, S.

Constraints

  • 0 < len(S) < 1000
  • The string consists of alphanumeric characters and spaces.

Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.

Output Format

Print the capitalized string, S.

Sample Input

chris alan

Sample Output

Chris Alan

 

Possible Solutions

Let us now solve the given problem using possible ways. The following code is already given in the hacker rank editor.

import math
import os
import random
import re
import sys

# Complete the solve function below.
def solve(s):

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

We need to complete the function in order to solve the problem.

 

Solution-1: Using for loop

Now, we will solve the problem using for loop and then we will explain the code in detail.

import math
import os
import random
import re
import sys

def solve(s):
    s=s.casefold()
    for i in range(len(s)):
        if s[i].isalpha()==True and (s[i-1]==" " or i==0):
            s=s[:i]+s[i].upper()+s[i+1:]
    k=str(s)
    return k

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

This solution defines a function "solve" which takes a string as input. The input string is first converted to lowercase using the "casefold" method. Then, the code iterates through each character in the string and checks if it's an alphabet (using the "isalpha" method) and if the previous character is a space or if the current character is the first character of the string. If both conditions are met, the character is converted to uppercase by concatenating the substring before the character, the uppercase version of the character, and the substring after the character. Finally, the transformed string is returned as a result of the function.

 

Solution-2: Using a user-defined function

Now we will define a function that will help us to solve the given problem.

import math
import os
import random
import re
import sys

def capitalize(match_obj):
    return match_obj.group().upper()

def solve(s):
    return re.sub('^\w| \w', capitalize, s)
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

This solution also defines a function "solve" which capitalizes the first letter of each word in a given string and returns the transformed string. The function utilizes the re (regular expression) module's "sub" method to perform the capitalization. The "capitalize" function is defined as a helper function that takes a match object as input and returns the capitalized version of the matched string. The "solve" function uses the "sub" method to substitute each match of the pattern "^\w| \w" (start of the string or a space followed by a word character) with the result of the "capitalize" function. Finally, the code writes the result of the "solve" function to a file specified by the environment variable "OUTPUT_PATH.

 

Solution-3: Using .join() method

We will now use the .join() method to solve the given problem.

import math
import os
import random
import re
import sys

def solve(s):
    return " ".join([name.capitalize() for name in s.split(" ")])

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

The solve() function first splits the input string "s" into a list of words using the "split" method with the separator " " (space). Then, it uses a list comprehension to iterate through each word in the list and apply the "capitalize" method to capitalize the first letter of each word. Finally, the "join" method is used to join the capitalized words back into a single string using the separator " " (space) and the resulting string is returned as the output of the function.

 

Solution-4: Using an if-else statement

Let us now use the if-else statement to solve the problem and then we will explain the code.

import math
import os
import random
import re
import sys

def solve(s):
    ans =""
    l = s.split(" ")
    for i in l:
        if i.isdigit():
            ans += i +" "
        else:
            ans+= i.capitalize()+" "
    return ans.strip()


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

This code takes in a string s as input and returns a new string ans as output. The input string s is split into a list of strings l using the split method, with a space as the separator. For each string i in l, if it is a digit (determined by the isdigit method), it is added to ans as is, followed by a space. If i is not a digit, the capitalize method is used to capitalize the first letter of i and the result is added to ans, followed by a space. Finally, the strip method is used to remove any trailing spaces in ans before it is returned as the final result.

 

Summary

In this short article, we discussed how we can solve the Capitalize problem. We solved the given problem using four different methods and explained each method in detail.

 

Further Reading

Question on Hacker Rank: Python Capitalize a [Strings]

 

Views: 33

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment