.split() – Splitting a string in Python

The .split() method splits a string into a list:

myString = "Hello my name is John"
x = myString.split()
print x

Results in a new list:

['Hello', 'my', 'name', 'is', 'John']

If we then split this by the commas:

myString = "Hello my name is John"
x = myString.split(",")
print x

We get a list which contains just this string:

['Hello my name is John']

Lets say we have our string split into a list:

myString = "Hello my name is John"
x = myString.split()
print x
Output: ['Hello', 'my', 'name', 'is', 'John']

But we only want the LAST item in that list, all we need to do is add [-1] to the end of the split method:

myString = "Hello my name is John"
x = myString.split()[-1]
print x
Output: John