Skip to content

Commit c645f2e

Browse files
committed
Add Title Case Conversion
[pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci added more test case and type hint [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci
1 parent 71b372f commit c645f2e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Diff for: strings/title.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
def convert_word(word: str) -> str:
2+
"""
3+
Converts a string to capitalized case, preserving the input as is
4+
5+
>>> convert_word("Aakash")
6+
'Aakash'
7+
8+
>>> convert_word("aakash")
9+
'Aakash'
10+
11+
>>> convert_word("AAKASH")
12+
'Aakash'
13+
14+
>>> convert_word("aAkAsH")
15+
'Aakash'
16+
"""
17+
18+
"""
19+
Convert the first character to uppercase if it's lowercase
20+
"""
21+
if "a" <= word[0] <= "z":
22+
word = chr(ord(word[0]) - 32) + word[1:]
23+
24+
"""
25+
Convert the remaining characters to lowercase if they are uppercase
26+
"""
27+
for i in range(1, len(word)):
28+
if "A" <= word[i] <= "Z":
29+
word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]
30+
31+
return word
32+
33+
34+
def to_title_case(input_str: str) -> str:
35+
"""
36+
Converts a string to title case, preserving the input as is
37+
38+
>>> to_title_case("Aakash Giri")
39+
'Aakash Giri'
40+
41+
>>> to_title_case("aakash giri")
42+
'Aakash Giri'
43+
44+
>>> to_title_case("AAKASH GIRI")
45+
'Aakash Giri'
46+
47+
>>> to_title_case("aAkAsH gIrI")
48+
'Aakash Giri'
49+
"""
50+
51+
words = input_str.split()
52+
title_case_str = [convert_word(word) for word in words]
53+
54+
return " ".join(title_case_str)
55+
56+
57+
if __name__ == "__main__":
58+
from doctest import testmod
59+
60+
testmod()

0 commit comments

Comments
 (0)