Think before you speak, read before you think.

python分割字符串split,filter

现有字符串,需要取出用空格分隔的第一段,操作如下

>>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
>>> product_model.split(' ')[0]
 'WS-C2960G-24TC-L'

不带参数的split(),会把所有空格(空格符、制表符、换行符)当作分隔符,如果有这些“空格”,则可这样写

>>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
>>> product_model.split()[0]
截取 1 到 最后
>>> product_model.split()[1:]

使用filter更多的是过滤,根据

>>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
>>> filter(None, product_model.split('-'))
 ['WS', 'C2960G', '24TC', 'L ', ' Fixed Module 0']

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *