Skip to content

Commit 4a3935e

Browse files
0APOCALYPSE0sedatguzelsemme
authored andcommitted
Add Title Case Conversion (TheAlgorithms#10439)
[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 updated naming convention
1 parent cdf8872 commit 4a3935e

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: strings/title.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
def to_title_case(word: str) -> str:
2+
"""
3+
Converts a string to capitalized case, preserving the input as is
4+
5+
>>> to_title_case("Aakash")
6+
'Aakash'
7+
8+
>>> to_title_case("aakash")
9+
'Aakash'
10+
11+
>>> to_title_case("AAKASH")
12+
'Aakash'
13+
14+
>>> to_title_case("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 sentence_to_title_case(input_str: str) -> str:
35+
"""
36+
Converts a string to title case, preserving the input as is
37+
38+
>>> sentence_to_title_case("Aakash Giri")
39+
'Aakash Giri'
40+
41+
>>> sentence_to_title_case("aakash giri")
42+
'Aakash Giri'
43+
44+
>>> sentence_to_title_case("AAKASH GIRI")
45+
'Aakash Giri'
46+
47+
>>> sentence_to_title_case("aAkAsH gIrI")
48+
'Aakash Giri'
49+
"""
50+
51+
return " ".join(to_title_case(word) for word in input_str.split())
52+
53+
54+
if __name__ == "__main__":
55+
from doctest import testmod
56+
57+
testmod()

0 commit comments

Comments
 (0)