View Full Version : Python: .split vs. .join
filifunk
September 5th, 2009, 02:39 PM
I don't understand why .split() and .join() can't be used in the same way. For instance, this works:
grocery_list: "Milk 2\nEggs 12"
grocery_list.split()
but this doesn't
grocery_list.join()
in fact I have to do this:
"".join(grocery_list)
why do most functions work like split() but join() works differently?
Just curious, maybe they're different types of functions?
ghostdog74
September 5th, 2009, 05:03 PM
grocery_list.join()
if you do that , the interpreter will give you errors. join() needs an argument.
slavik
September 5th, 2009, 06:34 PM
because in python, object.join(args) will join args together with object between them.
tjwilli
September 5th, 2009, 06:50 PM
I don't understand why .split() and .join() can't be used in the same way. For instance, this works:
grocery_list: "Milk 2\nEggs 12"
grocery_list.split()
but this doesn't
grocery_list.join()
in fact I have to do this:
"".join(grocery_list)
why do most functions work like split() but join() works differently?
Just curious, maybe they're different types of functions?
Maybe because they are basically opposites? split() breaks up a string into a sequence, join() concatenates a sequence into a string.
>>> grocery_list="Milk 2\nEggs 12"
>>> grocery_list.split()
['Milk', '2', 'Eggs', '12']
>>> ' '.join(grocery_list.split())
'Milk 2 Eggs 12'
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.