I have a variable that contains two words separated by a space, and I want to split it into two variables, one for each word. How would I do this?
As an example, my string would be
hello there and I want to split it into the variables
s = 'hello there' word1, word2 = s.split()
will do this for you. E.g.,
In : s = 'hello there' In : word1, word2 = s.split() In : print word1 hello In : print word2 there
split() is quite versatile, you can also specify other characters to split on. For more information on
split() see http://docs.python.org/library/stdtypes.html?highlight=split#str.split
You should use
string.split(s[, sep[, maxsplit]]):
s = "hello world" word1, word2 = s.split(' ', 1)
It splits a string into a list by the char you provide as an argument. Default is a space, but I'm using it as a parameter just to make it clearer.
You can also provide the
maxsplit argument and make sure the string gets splitted no more than
maxsplit times (like in our string - we must have exatly one split, because we're inserting the splitted words into excatly two variables.).
word1, word2 = 'hello there'.split()