split string in python to get one value?

Assign the first item directly to the variable.

>>> string = 'Sam-Person'
>>> name = string.split('-')[0]
>>> name
'Sam'

You can specify maxsplit argument, because you want to get only the first item.

>>> name = string.split('-', 1)[0]

Leave a Comment