11

Need help, let's assume that I have a string 'Sam-Person' in a variable called 'input'

name, kind = input.split('-')

By doing the above, I get two variable with different strings 'Sam' and 'Person'

is there a way to only get the first value name = 'Sam' without the need of the extra variable 'kind' and without having to work with lists?

When doing this, assuming that I was going to get only 'Sam':

name = input.split('-')

I get a list, and then I can access the values by index name[0] or name[1], but it is not what I want, I just want to directly get 'Sam' into the variable 'name', is there a way to do that or an alternative to split?

2 Answers 2

22

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]
3
  • One more question, where did you manage to learn that? any specif book?
    – espktro
    Jul 1, 2017 at 9:20
  • @espktro, Python tutorial is a good starting point.
    – falsetru
    Jul 1, 2017 at 9:23
  • we are adressing a sinlge index postition ('0' here). You can adress more then one by i.e. name = string.split('-') & print(name[0],name[1])
    – vrms
    Aug 29 at 9:02
4

If you don't need the second part of the split, you could instead try searching the string for the index of the first - character and then slicing to that index:

string[:string.index('-')]

This is a little bit faster than splitting and discarding the second part because it doesn't need to create a second string instance that you don't need.

Be aware that this code will raise an exception if there's no - in the string, as did your original code. A solution using split like falsetru's will return the full string instead (which may or may not be better).

2
  • Nice alternative, I also think is better and it is what I really was looking for.I don't need the second part of the string at all.
    – espktro
    Jul 1, 2017 at 9:59
  • This should be the right answer, as it is not necessary to scan the entire string (think about a huge string). Thank you for the proposal
    – Dos
    May 28, 2021 at 11:58

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.