Skip to content

Commit 9c9bb29

Browse files
committed
Improve capitalize(): add Unicode support and handle leading spaces
1 parent a051ab5 commit 9c9bb29

File tree

1 file changed

+15
-15
lines changed

1 file changed

+15
-15
lines changed

strings/capitalize.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
def capitalize(sentence: str) -> str:
22
"""
3-
Capitalizes the first letter of a sentence or word.
3+
Capitalizes the first alphabetical character of a sentence.
44
5+
Examples:
56
>>> capitalize("hello world")
67
'Hello world'
7-
>>> capitalize("123 hello world")
8-
'123 hello world'
9-
>>> capitalize(" hello world")
10-
' hello world'
11-
>>> capitalize("a")
12-
'A'
8+
>>> capitalize(" hello world")
9+
' Hello world'
10+
>>> capitalize("123 abc")
11+
'123 abc'
12+
>>> capitalize("ñandú bird")
13+
'Ñandú bird'
1314
>>> capitalize("")
1415
''
1516
"""
17+
1618
if not sentence:
1719
return ""
1820

19-
# Capitalize the first character if it's a lowercase letter
20-
# Concatenate the capitalized character with the rest of the string
21-
return sentence[0].upper() + sentence[1:]
22-
23-
24-
if __name__ == "__main__":
25-
from doctest import testmod
21+
# Find the first alphabetic character and capitalize it
22+
for idx, char in enumerate(sentence):
23+
if char.isalpha():
24+
return sentence[:idx] + char.upper() + sentence[idx+1:]
2625

27-
testmod()
26+
# If no alphabetic character exists, return the original string
27+
return sentence

0 commit comments

Comments
 (0)