Skip to content

Commit a048662

Browse files
committed
perf: optimize ASCII lowercase conversion
1 parent 27f92fb commit a048662

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

strings/lower.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1+
ASCII_UPPERCASE_START = ord("A")
2+
ASCII_UPPERCASE_END = ord("Z")
3+
ASCII_CASE_OFFSET = ord("a") - ord("A")
4+
5+
16
def lower(word: str) -> str:
27
"""
3-
Will convert the entire string to lowercase letters
8+
Convert ASCII uppercase letters in a string to lowercase.
49
510
>>> lower("wow")
611
'wow'
@@ -13,11 +18,15 @@ def lower(word: str) -> str:
1318
>>> lower("whAT")
1419
'what'
1520
"""
21+
result = []
22+
23+
for char in word:
24+
code = ord(char)
25+
if ASCII_UPPERCASE_START <= code <= ASCII_UPPERCASE_END:
26+
char = chr(code + ASCII_CASE_OFFSET)
27+
result.append(char)
1628

17-
# Converting to ASCII value, obtaining the integer representation
18-
# and checking to see if the character is a capital letter.
19-
# If it is a capital letter, it is shifted by 32, making it a lowercase letter.
20-
return "".join(chr(ord(char) + 32) if "A" <= char <= "Z" else char for char in word)
29+
return "".join(result)
2130

2231

2332
if __name__ == "__main__":

0 commit comments

Comments
 (0)