Hello guys I'm trying to creat a function that works similarly to split() function but I'm unable to make it count " " as an item and seperate it here is my code:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr, delimitor:
if i != " ":
A = i
elif A != "":
B.append(A)
A = ""
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
CodePudding user response:
You problem is that your for loop is ill defined.
What are you looping on? You are trying to look at argstr character by character. The delimitor is a constant.
Result:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr:
if i != " ":
A = i
elif A != "":
B.append(A)
A = ""
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
Another problem you have is that you aren't actually using the delimitor at all, instead redefining it to be " " in your code. An improvement would be:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr:
if i != delimitor:
A = i
elif A != "":
B.append(A)
A = ""
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
It's possible to make your code even cleaner, but this way it should already work properly.
I see that you are insistent on wanting a ' ' in your result array. First I must warn you that this isn't consistent with what str.split does, so if you want to imitate str.split, you shouldn't do that.
But if you want it, here is a simple solution to it:
def mysplit(argstr, delimitor):
A = ""
B = []
for i in argstr:
if i != delimitor:
A = i
elif i == delimitor:
if A != "":
B.append(A)
A = ""
B.append(delimitor)
if A != "":
B.append(A)
return B
print(mysplit('abc def',' '))
CodePudding user response:
because of this line:
for i in argstr, delimitor:
You're telling the for loop to iterate over those two variables, so it takes the entire string in argstr
as the first iteration.
replacing it with:
for i in argstr:
does what you want.