50

Possible Duplicate:
Python Split String

Is possible to directly split string into variables in one line, instead of using two lines. I'm sure that split would have two elements. Two lines example:

myString = "Anonym Anonymous"
a = myString.split()
firstName,lastName = a[0],a[1]
4
  • 4
    Are you asking how to write firstName,lastName=myString.split()? Commented Jul 12, 2011 at 20:00
  • 1
    @larsmans: It's not intended to be an answer. I don't understand the question. I'm hoping that an example will clarify what they're trying to ask. Commented Jul 12, 2011 at 20:03
  • But this is about python's syntax not about the function Commented Jul 14, 2011 at 8:42
  • Looking at this closed question, the number of views clearly indicates it's about something else, than existing duplicate question. This one is about python's syntax in combination with splitting of string, rather than splitting a string alone. One could deduce the answer from knowledge of two basic things, but this isn't a common case for complete python newbies, who are still learning - as I was 10 years ago,... Commented Dec 28, 2021 at 10:46

2 Answers 2

86

firstName, lastName = myString.split() should do it if you're sure it will return 2.

Better is firstName, lastName = myString.split(' ', 1)

Sign up to request clarification or add additional context in comments.

3 Comments

What is better depends on the circumstances. If more or less than two values is an error, the first option is better as it will throw an appropriate exception.
Or firstName, _, lastName = myString.partition(' ')
I agree with larsmans. I would usually prefer raise an exception when the input does not meet my expectations.
9
firstname, lastname = "Anonym Anonymous".split()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.