Files
Python/strings/capitalize.py
Milad Khoshdel a8c5616857 Simplify Capitalize Function (#12879)
* Simplify the capitalize function using ASCII arithmetic to make the algorithm five times faster.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update capitalize.py

* Update capitalize.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
2025-08-24 13:07:39 +03:00

28 lines
637 B
Python

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 ""
# Capitalize the first character if it's a lowercase letter
# Concatenate the capitalized character with the rest of the string
return sentence[0].upper() + sentence[1:]
if __name__ == "__main__":
from doctest import testmod
testmod()