Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions strings/capitalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,11 @@ def capitalize(sentence: str) -> str:
>>> capitalize("")
''
"""
if not sentence:
return ""

# Capitalize the first character if it's a lowercase letter
# Concatenate the capitalized character with the rest of the string
return sentence[0].upper() + sentence[1:]
# Slicing keeps this safe for empty strings.
return sentence[:1].upper() + sentence[1:]


if __name__ == "__main__":
Expand Down
30 changes: 16 additions & 14 deletions strings/split.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,36 @@
def split(string: str, separator: str = " ") -> list:
def split(string: str, separator: str = " ") -> list[str]:
"""
Will split the string up into all the values separated by the separator
(defaults to spaces)
Split string into values separated by separator.

>>> split("apple#banana#cherry#orange",separator='#')
>>> split("apple#banana#cherry#orange", separator="#")
['apple', 'banana', 'cherry', 'orange']

>>> split("Hello there")
['Hello', 'there']

>>> split("11/22/63",separator = '/')
>>> split("11/22/63", separator="/")
['11', '22', '63']

>>> split("12:43:39",separator = ":")
>>> split("12:43:39", separator=":")
['12', '43', '39']

>>> split(";abbb;;c;", separator=';')
>>> split(";abbb;;c;", separator=";")
['', 'abbb', '', 'c', '']
"""

split_words = []
if len(separator) != 1:
raise ValueError("separator must be exactly one character")

parts: list[str] = []
start = 0

last_index = 0
for index, char in enumerate(string):
if char == separator:
split_words.append(string[last_index:index])
last_index = index + 1
if index + 1 == len(string):
split_words.append(string[last_index : index + 1])
return split_words
parts.append(string[start:index])
start = index + 1

parts.append(string[start:])
return parts


if __name__ == "__main__":
Expand Down