Python string get leading characters up to first comma

I have the following string:

strIn = "Head,0.000235532,0.43656735"

I would like to retrieve from this a variable type = "Head" and an array vals = [0.000235532,0.43656735]

How can I do this using Python? I've considered using strIn[0],...,strIn[5] to get the type, but then I realized I'll get types of various lengths. Thanks.


If you're using Python 3, you can do

type_, *vals = strIn.split(',')
vals = [float(v) for v in vals]  # Convert list of strings to list of floats.

This uses str.split to split the string into a list based on the provided character, and then uses Python 3's extended tuple unpacking to put the first value into type_ and the remaining values into vals . See this answer for more discussion on how to use tuple unpacking.

If you're on Python 2 you can't use the extended unpacking syntax, so you have to add an additional step:

str_list = strIn.split(',')
type_ = str_list[0]
vals = [float(v) for v in str_list[1:]]

As you are in python2 first split with , then use slicing and float function :

>>> none=strIn.split(',')[0]
>>> none
'Head'
>>> vals=map(float,strIn.split(',')[1:])
>>> vals
[0.000235532, 0.43656735]

As type is a built-in name recommended that dont use it !

链接地址: http://www.djcxy.com/p/53558.html

上一篇: Python:元组赋值,同时转换类型

下一篇: Python字符串会将主要字符变成第一个逗号