先上代码再解释:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
s = "target_link_libraries(qtinfra_canvas \n PUBLIC Qt4::QtGui \nPRIVATE infra common qtinfra_util)"
s1 = s[s.index('(')+1:s.index(')')]
s2 = s1.split(" ")
s3 = map(lambda s: s.strip(), s2)
s4 = filter(None, s3)
print s1
print s2
print s3
print s4
'''Output:
qtinfra_canvas
PUBLIC Qt4::QtGui
PRIVATE infra common qtinfra_util
['qtinfra_canvas', '\n', '', '', 'PUBLIC', 'Qt4::QtGui', '', '', '', '\nPRIVATE', 'infra', 'c
['qtinfra_canvas', '', '', '', 'PUBLIC', 'Qt4::QtGui', '', '', '', 'PRIVATE', 'infra', 'commo
['qtinfra_canvas', 'PUBLIC', 'Qt4::QtGui', 'PRIVATE', 'infra', 'common', 'qtinfra_util']
'''
去除字符串里面的\n:str.strip()
去除list里面的\n(不减少元素数量):newStr = map(lambda s: s.strip(), oldStr)
去除list里面为空的元素:newStr = filter(None, oldStr)
切分字符串(可以结合正则表达式来做:re模块(需import re)里面的re.split()):
用空格:s2 = s1.split(" ")
用逗号:s2 = s1.split(",")