-1

I have a list:

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']

and i would like to iterate through all of the items, replace / with - using re.sub, and skip the element if it is not a string. What am i doing wrong syntactically in this list comprehension to check if x is a string prior to running my re.sub ?

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

Error output:

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

Process finished with exit code 1
dobbs
  • 899
  • 4
  • 17
  • 36

2 Answers2

2

The if clause for the for iterations should come after the for:

>>> 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']

And in your case, since it's a simple substitution you don't need to use re.sub(). Use str.replace() instead:

>>> blah = [x.replace('/', '-') for x in v if isinstance(x, str)]
aneroid
  • 11,031
  • 3
  • 33
  • 54
0

You have the if and for clauses in the wrong order--the for clause comes before the if clause. Try

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

I then get for blah,

['4-29-2016 8:25:58 AM',
 '5-25-2016 2:22:22 PM',
 'True',
 'Foo',
 '4-20-1969 4:19:59 PM']
Rory Daulton
  • 19,351
  • 5
  • 34
  • 45