简体   繁体   中英

Where am I going wrong with this list comprehension?

I want to extract the 4 digit year (2000) from a string or return None or NaN if its not present.

w = 'A70-11370; reprint; rolled; 2000; 26.5 x 38.5'

I tried this but I get a syntax error.

[int(i) for i in w.split(';') if i.isnumeric() else np.nan]

I'd strip the whitespace and reposition the validation check:

In[0]: [int(i.strip()) if str(i.strip()).isnumeric() else np.NaN for i in w.split(';')]
Out[0]: [nan, nan, nan, 2000, nan]

This must surely work

x=w.split('; ')

if x[3] == ' ':
    print ("null")
else:
    print (x[3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM