Skip to content

Commit b331992

Browse files
authored
Add Title Case Conversion
1 parent 71b372f commit b331992

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

strings/title.py

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

0 commit comments

Comments
 (0)