Defining separator for split and join method in python
In the code given below the separator is defined by two separate ways for join as well as split methods.
For join method separator (",") is defined before the method on the contrary sperator is defined inside the argument parenthesis for split method. on what basis is the syntax for these methods are constructed. I am new to programming and I find it little confusing. Any help in this regard will be much appreciated. Thank you
print (txt.split(",")) #sep defined inside parenthesis
print(",".join(txt2)) #sep defined before the method
That is because both methods are of string class.
You invoke the split() method intending to part away a string based on a separator - in this case the syring here is txt variable.
But you invoke the join command on a string which is supposed to be the glue bonding together a split apart *list*. In this case though, the string is the ",".
To my understanding, both split and join are "methods of str object". In your code, "," is a string and so is txt. Thus, to use these methods, you should type "string" beforehand.
Of course, you can define a new function by your self, such as
def split(txt, sep) :
def join(list, sep) :
if you want to, but that may be unnecessary.
str.join("," , ["ef", "gh"])
str.split("ab,bc" , ",")