Capitalize First Letter in Python | Challenge

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Python, we can capitalize the first letter of a string using various methods. In this challenge, you are required to write a function that capitalizes the first letter of a given string.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") subgraph Lab Skills python/comments -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} python/booleans -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} python/conditional_statements -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} python/lists -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} python/tuples -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} python/function_definition -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} python/default_arguments -.-> lab-13064{{"`Capitalize First Letter in Python | Challenge`"}} end

Capitalize String

Problem

Write a Python function called capitalize_string(s, lower_rest=False) that takes a string as an argument and returns a new string with the first letter capitalized. The function should have an optional parameter lower_rest which, if set to True, converts the rest of the string to lowercase.

Example

capitalize_string('hello world') ## 'Hello world'
capitalize_string('hello world', True) ## 'Hello world'

Summary

In this challenge, you have learned how to capitalize the first letter of a string in Python. You can use the capitalize() method or write a custom function to achieve the same result.

Other Python Tutorials you may like