Python 检查列表中的变量是否为字符串

Python 检查列表中的变量是否为字符串,python,list-comprehension,Python,List Comprehension,我有一份清单: v=['4/29/2016 8:25:58 AM','5/25/2016 2:22:22 PM','True','Foo',1','4/20/1969 4:19:59 PM'] 我希望遍历所有的项,替换/为-using re.sub,如果元素不是字符串,则跳过它。在运行re.sub之前,检查x是否为字符串,在此列表理解中,我在语法上犯了什么错误 blah=[re.sub/,'-',如果isinstancex,则为x,在v中为x的str] 错误输出: blah = [ re

我有一份清单:

v=['4/29/2016 8:25:58 AM','5/25/2016 2:22:22 PM','True','Foo',1','4/20/1969 4:19:59 PM']

我希望遍历所有的项,替换/为-using re.sub,如果元素不是字符串,则跳过它。在运行re.sub之前,检查x是否为字符串,在此列表理解中,我在语法上犯了什么错误

blah=[re.sub/,'-',如果isinstancex,则为x,在v中为x的str]

错误输出:

    blah = [ re.sub("/", '-', x ) if isinstance(x, str) for x in v ]
                                                          ^
SyntaxError: invalid syntax

Process finished with exit code 1
if和for子句的顺序错误。for子句位于if子句之前。试一试

blah = [ re.sub("/", '-', x ) for x in v if isinstance(x, str) ]
然后我得到了什么

for迭代的if子句应位于for之后:

在您的情况下,因为它是一个简单的替换,所以您不需要使用re.sub。改用:

['4-29-2016 8:25:58 AM',
 '5-25-2016 2:22:22 PM',
 'True',
 'Foo',
 '4-20-1969 4:19:59 PM']
>>> blah = [re.sub("/", '-', x ) for x in v if isinstance(x, str)]
>>> blah
['4-29-2016 8:25:58 AM', '5-25-2016 2:22:22 PM', 'True', 'Foo', '4-20-1969 4:19:59 PM']
>>> blah = [x.replace('/', '-') for x in v if isinstance(x, str)]