+ 1
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 txt="ab,bc" txt2=["ef","gh"] print (txt.split(",")) #sep defined inside parenthesis print(",".join(txt2)) #sep defined before the method
2 odpowiedzi
+ 6
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 ",".
0
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.
Remember:
object.method
",".join(...)
"ab,bc".split(...)
Of course, you can define a new function by your self, such as
def split(txt, sep) :
......
or
def join(list, sep) :
......
if you want to, but that may be unnecessary.
Edit :
try these:
str.join("," , ["ef", "gh"])
str.split("ab,bc" , ",")
Note that:
class.method_name(self, *args)