-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcapital_split.py
More file actions
44 lines (39 loc) · 1.17 KB
/
capital_split.py
File metadata and controls
44 lines (39 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
Write a function to split a string at each capital letter.
If there are no capital letters in the string return an empty list.
input:'Helloworld'
output:['Hello', 'World']
Reason: The input string is split at each capital letter, resulting in two strings: 'Hello' and 'World'.
Input:'ThisIsATest'
Output:['This', 'Is', 'A', 'Test']
"""
def split_at_capitals_iterative(s):
if not any(c.isupper() for c in s):
return []
result = []
current_word = ''
for char in s:
if char.isupper():
if current_word:
result.append(current_word)
current_word = char
else:
current_word += char
if current_word:
result.append(current_word)
return result
# Example usage:
input_string = 'HelloWorld'
output = split_at_capitals_iterative(input_string)
print(output) # Output: ['Hello', 'World']
# Using re
# import re
# def split_at_capitals_regex(s):
# if not any(c.isupper() for c in s):
# return []
# return re.findall(r'[A-Z][a-z]*', s)
#
# # Example usage:
# input_string = 'HelloWorld'
# output = split_at_capitals_regex(input_string)
# print(output) # Output: ['Hello', 'World']