开发者

Python: split a full name "First Last", "First Middle Last," etc ... into separate variables?

开发者 https://www.devze.com 2022-12-22 03:56 出处:网络
I\'m looking for the best way to write a function that takes a string in the form: \"First\" \"First Last\"

I'm looking for the best way to write a function that takes a string in the form:

"First" "First Last" "First Middle Last" "First M. Last" "First Second Third Last"

And can return a python a list with each of the values separated.

Thanks.开发者_Go百科


Use the split function:

>>> s = "First Middle Last"
>>> s.split(" ")
['First', 'Middle', 'Last']


Andrew Hare is correct, however if you want to split on whitespace, loose the " " parameter.
The default is whitespace and is more robust:

>>> '   a b     c   '.strip().split(" ")
['a', 'b', '', '', '', '', 'c']

>>> '   a b     c   '.strip().split()
['a', 'b', 'c']
0

精彩评论

暂无评论...
验证码 换一张
取 消