Capitalize in Python

Published on 24 October 2021 (Updated: 24 October 2021)

Capitalize in Python

In this article, we will see how to implement Capitalize program using Python.

How to Implement Solution

Let’s take a look on code for capitalize.py:

import sys

def capitalize(input):
    if len(input) > 0:
        print(input[0].capitalize() + input[1:])


if __name__ == '__main__':
    if(len(sys.argv) == 1 or len(sys.argv[1]) == 0):
        print('Usage: please provide a string')
    else:
        capitalize(sys.argv[1])

Now, we will consider this code block by block on the order of execution.

if __name__ == '__main__':
    if(len(sys.argv) == 1 or len(sys.argv[1]) == 0):
        print('Usage: please provide a string')
    else:
        capitalize(sys.argv[1])

This code checks if the main module is run. If it is, it then checks if the length of argument string provided by the user is 1 or empty string. If it is, it then prints correct usage pattern. Otherwise, it passes control to capitalize function passing argument string provided by the user.

def capitalize(input):
    if len(input) > 0:
        print(input[0].capitalize() + input[1:])

If the length provided by the user string is greater than 0, then it prints first letter of the string capitalized and concatenates the rest of the string.

How to Run Solution

If we want to run this program, we should probably download a copy of Capitalize in Python. After that, we should make sure we have the latest Python interpreter. From there, we can simply run the following command in the terminal:

python capitalize.py

Alternatively, we can copy the solution into an online Python interpreter and hit run.

Further Reading