Connect with us

HackerRank

Capitalize – HackerRank Python Solution

The goal is to capitalize the first letter of each word in a Python string while preserving the original whitespace.

Published

on

The code in this tutorial article serves as the Python solution to the HackerRank problem called ‘Capitalize!‘ It defines a function solve that takes a string s as input and returns a modified version of the string. The Python function uses a one-line solution to capitalize the first letter of each word while preserving the original whitespace. It splits the input string s using a regular expression re.split(r'(\s+)', s), thanks to the re module, which divides the string based on any sequence of whitespace characters. This essentially captures the whitespaces as separate elements.

def solve(s):
    # One-line solution
    return "".join(
        [c.capitalize() if c[0].isalpha() else c for c in re.split(r"(\s+)", s)]
    )
    # Using re.split(r'(\s+)', s) helps retain any number of whitespaces after joining back the tokens.

The list comprehension processes each split segment: if the segment starts with an alphabetic character, it capitalizes the segment; otherwise, it leaves it unchanged. The Capitalize solution function then joins these processed segments back into a single string using "".join(), which preserves the original whitespace structure in the output.

Trending