In: Computer Science
Python
Write a function str_slice(s) to slice sentence into single word by
their spaces and punctuations and returns a list.
You cannot use split(), join() method for this define
function
Example:
>>>str_slice(‘Hi, I like it!!’)
[‘Hi’, ‘, ’, 'I', ‘ ‘, ‘like’, ‘ ‘, ‘it’, ‘!!’]
PYTHON CODE
#function str_slice(s) to slice sentence into single word
#by their spaces and punctuations
#returns a list
def str_slice(s):
ind = 0#starting index
str_array = []#string sliced and stored in str_array
space = ' '#space character
punctuations = "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"#punctuations characters
while ind < len(s):
tempStr = ''#store slicing string
if s[ind] not in space and s[ind] not in punctuations:#if the character is not space or punctuations, then sliced separately
while ind < len(s) and s[ind] not in space and s[ind] not in punctuations:
tempStr += s[ind]
ind += 1
elif s[ind] in space:#orelse if it is space, then sliced separately
while ind <len(s) and s[ind] in space:
tempStr += s[ind]
ind += 1
elif s[ind] in punctuations:#if it is any punctuation, then sliced separately
while ind <len(s) and s[ind] in punctuations:
tempStr += s[ind]
ind += 1
str_array.append(tempStr)#add sliced string to the array
return str_array#return array
PYTHON CODE SCREENSHOT
OUTPUT SCREENSHOT