mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-24 21:41:08 +00:00
ade2837e41
* Update capitalize.py * Update strings/capitalize.py --------- Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
33 lines
856 B
Python
33 lines
856 B
Python
from string import ascii_lowercase, ascii_uppercase
|
|
|
|
|
|
def capitalize(sentence: str) -> str:
|
|
"""
|
|
Capitalizes the first letter of a sentence or word.
|
|
|
|
>>> capitalize("hello world")
|
|
'Hello world'
|
|
>>> capitalize("123 hello world")
|
|
'123 hello world'
|
|
>>> capitalize(" hello world")
|
|
' hello world'
|
|
>>> capitalize("a")
|
|
'A'
|
|
>>> capitalize("")
|
|
''
|
|
"""
|
|
if not sentence:
|
|
return ""
|
|
|
|
# Create a dictionary that maps lowercase letters to uppercase letters
|
|
# Capitalize the first character if it's a lowercase letter
|
|
# Concatenate the capitalized character with the rest of the string
|
|
lower_to_upper = dict(zip(ascii_lowercase, ascii_uppercase))
|
|
return lower_to_upper.get(sentence[0], sentence[0]) + sentence[1:]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
from doctest import testmod
|
|
|
|
testmod()
|