[Solved] When should we use split() in Python?


I don’t understand the confusion. The split() function return a list of all subparts of your string by removing all occurences of the given argument.

For example, if you have the following string : “Hello world!” and split this one by split(“o”) then your output will be : [“Hell”, ” w”, “rld!”]

With a code:

str = "Hello world!"
split_str = str.split("o")

print "str has type", type(str), "with the value", str, "\n"
print "split_str has type", type(split_str), "with the value", split_str

Then, the output will be :

str has type string with the value Hello world!

split_str has type list with the value [“Hell”, ” w”, “rld!”]

So, if you have a string that represents a sequence of different integers separated by space: you could operate with this solution.

input_integers = raw_input().split(" ") # splits the given input string
numbers = [int(x) for x in input_integers] # iteration to convert from string to int
numbers = sorted(numbers) # makes a sort on the integer list
print numbers # display

It’s a very basic use of string so, for the next time, have the reflex to read the doc. It’s the first tool that you may read to have your solution.

solved When should we use split() in Python?