-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathcustom_split.py
47 lines (43 loc) · 1.21 KB
/
custom_split.py
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
45
46
47
#!/usr/bin/python
# Date: 2020-08-15
#
# Description:
# Split string by space considering substrings enclosed between quotes as
# single string.
#
# Complexity:
# O(n)
def custom_split(log):
"""
Splits string with space considering subsrtings enclosed between quotes as
single string.
"""
running_substring = False
log = log.strip()
i = -1
splitted_string = []
token = []
while i < len(log) - 1:
i += 1
if log[i] in ('"', "'"):
if running_substring:
running_substring = False
splitted_string.append(''.join(token))
token = []
else:
running_substring = True
elif log[i] == ' ':
if running_substring:
token.append(log[i])
elif token:
splitted_string.append(''.join(token))
token = []
else:
token.append(log[i])
if token:
splitted_string.append(''.join(token))
return splitted_string
assert custom_split(
'This is a "python project"') == ['This', 'is', 'a', 'python project']
assert custom_split(
'This is a python project') == ['This', 'is', 'a', 'python', 'project']