Home > Enterprise >  A function similar to split()
A function similar to split()

Time:02-13

I was wondering what the A != "" does in this code.

def mysplit(strng):
A = ""
B = []
for i in strng:
    if i != " ":
        A  = i
    elif A != "":
        B.append(A)
        A = ""
# Append last word
if A != "":
    B.append(A)

return(B)

This is the code that I found for a uni project that i need, but that piece of code doesn't make sense to me, isnt it just empty? how are you gonna get an empty character in your text apart from the spaces?

also, do strings have positions?

CodePudding user response:

Yes, strings have index from 0 to n-1 just like in a string. Eg: A = "abcd", print(a[2]) //output: "c"

As for your code, i iterates through every element in the input string, and it is appended to A if i is not a "space". When it is a "space", A is appended to B list and A is cleared in order to get the next word. For the last word, since there is no space in the end, the string A does not get appended to B list, so it is done separately outside the for loop.

CodePudding user response:

What this function will do is accept a string as an argument, and then loop through each character of the string.

The first if will add character by character to A until it reaches a space and when this occurs it will dump the contents of A into B as a [list], which will be a full word, and then RESET A to '', that way it will continue to read char by char the next word.

By the end of the loop, B will contain each word of the string as items in a list and return.

def mysplit(strng):
A = ""
B = []
for i in strng: #Loop through each char in string
    if i != " ": #if char is not a space
        A  = i #add character to A
    elif A != "": #if A is not empty
        B.append(A) #add whatever is in A to B as a list (full word)
        A = "" #resets A to be empty
if A != "": #if A is empty
    B.append(A)

return(B)

To answer your other question, yes strings do have index positions. If you python print('Hello World'[0:5]) This will return: Hello

  • Related