Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into different variables instead of array in Python [duplicate]

Tags:

python

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] 
like image 819
kravemir Avatar asked Jul 12 '11 19:07

kravemir


People also ask

How do you split a string into multiple variables in Python?

Split String by Character In Python, we have an in-built method called list() to split the strings into a sequence of characters. The list() function accepts one argument which is a variable name where the string is stored.

How do I split a string into separate strings in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Can split () take two arguments?

split() only works with one argument, so I have all words with the punctuation after I split with whitespace.


2 Answers

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

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

like image 63
TorelTwiddler Avatar answered Sep 24 '22 21:09

TorelTwiddler


firstname, lastname = "Anonym Anonymous".split() 
like image 43
Christopher Bruns Avatar answered Sep 24 '22 21:09

Christopher Bruns