Many programming languages, including Python, support an operation like this:
", ".join(["1","2","3"])
which returns the string
"1, 2, 3"
I understand that this is the case, but I don't understand the design decision behind it - surely it would be more semantically valid to perform the join
operation on the list, like so:
["1","2","3"].join(", ")
If anyone could explain the design decision and shed some light on it I'd appreciate it.
Edit: It looks like Javascript has the join
method on the list; if anyone has examples for which convention particular languages follow, feel free to comment/answer about the choice in that particular language too.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer. Use the list() class to convert the map object to a list.
To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use = to store the list in a variable.
For python, there are a few arguments against it. First, if it is a string method that accepts an arbitrary iterable, then you only need to support the join
method on string objects and it automagically works with anything iterable. Otherwise, custom iterable objects would also need to support a join
method, etc. etc.
consider:
", ".join(["1","2","3"])
", ".join(("1","2","3"))
", ".join(str(x) for x in xrange(1,4))
", ".join({'1':None,'2':None,'3':None})
", ".join({'1','2','3'}) #set literal syntax -- python2.7+
", ".join("123")
6 different types all supported very simply by a single method (and I've only touched builtin types).
Second, you can only join
a list if everything in it is a basestring
type. It seems silly to provide a method on a list which would raise an exception if you used it on a list with the wrong contents -- At least, the API here seems somewhat tricky (to me). Of course, you could argue that list.remove
can raise an exception if called with the wrong arguments. And that's true -- But that in general you're only removing a single item. It operates on a lower level than join
should. Of course, this argument is weaker than the first one I proposed, so if you don't like it, just fall back on argument 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With