-1

I want to cut a string in two and I'm doing this.

parts = str.split("street one")

Would it be better to do this? Or more efficient?

parts = "street one".split()
Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
RodriKing
  • 822
  • 2
  • 10
  • 20

3 Answers3

2

Given an object obj of type Class, the following two notations are equivalent:

obj.method(arg)
Class.method(obj, arg)

So in your case, these two are equivalent:

"street one".split()
str.split("street one")

And these two are equivalent:

"street one".split(" ")
str.split("street one", " ")
Martin Frodl
  • 667
  • 4
  • 11
  • using `%timeit`, the two seem to be almost identical from an efficiency standpoint as well – G. Anderson Dec 13 '18 at 16:53
  • But, If the definition of the function is `str.split(self, separator, maxsplit):` .If you use the first way `str.split("street one")`The string that you pass to the function is passed as self? On second thought, I think the second way is better. – RodriKing Dec 14 '18 at 08:00
  • The string will be captured as the `self` parameter in *all* cases, even when calling `"street one".split()`. – Martin Frodl Dec 14 '18 at 08:16
1

Both are valid, and correct, Python. So the question is simply which is stylistically preferable and more "Pythonic". I would say that the second is Pythonic and should be preferred; but the first is not "wrong".

I am not aware of any performance differences between the two forms.

Jack Aidley
  • 19,439
  • 7
  • 43
  • 70
  • But, If the definition of the function is `str.split(self, separator, maxsplit):` .If you use the first way `str.split("street one")` The string that you pass to the function is passed as self? On second thought, I think the second way is better. – RodriKing Dec 14 '18 at 08:00
0

Both of them perform the same task of splitting.i.e-> ['street','one']. Anyway you do it, it's pretty much the same

Suvab
  • 41
  • 1
  • 5