Skip to content

Add Title Case Conversion #10439

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 14, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions strings/title.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
def to_title_case(word: str) -> str:
"""
Converts a string to capitalized case, preserving the input as is

>>> to_title_case("Aakash")
'Aakash'

>>> to_title_case("aakash")
'Aakash'

>>> to_title_case("AAKASH")
'Aakash'

>>> to_title_case("aAkAsH")
'Aakash'
"""

"""
Convert the first character to uppercase if it's lowercase
"""
if "a" <= word[0] <= "z":
word = chr(ord(word[0]) - 32) + word[1:]

"""
Convert the remaining characters to lowercase if they are uppercase
"""
for i in range(1, len(word)):
if "A" <= word[i] <= "Z":
word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]

return word


def sentence_to_title_case(input_str: str) -> str:
"""
Converts a string to title case, preserving the input as is

>>> sentence_to_title_case("Aakash Giri")
'Aakash Giri'

>>> sentence_to_title_case("aakash giri")
'Aakash Giri'

>>> sentence_to_title_case("AAKASH GIRI")
'Aakash Giri'

>>> sentence_to_title_case("aAkAsH gIrI")
'Aakash Giri'
"""

return " ".join(to_title_case(word) for word in input_str.split())


if __name__ == "__main__":
from doctest import testmod

testmod()