Capitalize First Letter in Python

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-13596{{"`Capitalize First Letter in Python`"}} python/booleans -.-> lab-13596{{"`Capitalize First Letter in Python`"}} python/conditional_statements -.-> lab-13596{{"`Capitalize First Letter in Python`"}} python/lists -.-> lab-13596{{"`Capitalize First Letter in Python`"}} python/tuples -.-> lab-13596{{"`Capitalize First Letter in Python`"}} python/function_definition -.-> lab-13596{{"`Capitalize First Letter in Python`"}} python/default_arguments -.-> lab-13596{{"`Capitalize First Letter in Python`"}} end

Capitalize String

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.

def capitalize(s, lower_rest = False):
  return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])])
capitalize('fooBar') ## 'FooBar'
capitalize('fooBar', True) ## 'Foobar'

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