Lately I tried to figure out a question implementing split() function, objective is to complete a function that split a string with delimiters such as "-" or a path string with "/"s to a list of words in a recursive manner.
inputString = "Tadokoro-Kouji-114514"
expectedOutput = ["Tadokoro", "Kouji", "114514"]
Tried the solution using find(), is there any other possible solution without using linear functions?
def splitString(str, delim):
list=[]
i=str.find(delim)
if i!=-1:
list.append(str[0:i])
newStr=str[i 1:]
list.extend(splitString(newStr, delim))
else:
list.append(str)
return list
CodePudding user response:
It would be best not to use camelCase to name functions and variables in Python. Anyway, you can split a string into words with recursion something like this:
input_string = "Tadokoro-Kouji-114514"
words = []
def split_string(string, delim, head=''):
if string:
if string[0] == delim:
words.append(head)
return split_string(string[1:])
else:
return split_string(string[1:], head string[0])
else:
words.append(head)
return ''
split_string(input_string)
print(words)
