Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shortening if statements Python

Is there a way to shorten this:

if str(num[p]).find('0') == 
int(-1) and
str(num[p]).find('1') == int(-1) 
and str(num[p]).find('2') == 
int(-1) and str(num[p]).find('3') 
== int(-1) and 
str(num[p]).find('4') == int(-1) 
and str(num[p]).find('5') == 
int(-1) and str(num
[p]).find('6') == int(-1) and 
str(num[p]).find('7') == int(-1) 
and str(num[p]).find('8') == 
int(-1) and str(num[p]).find('9') 
== int(-1) and str
(num[p]).find('.') == int(-1):

Note:the num[p] is part of a for loop and is not an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’d write this as:

if not any(c in num[p] for c in "0123456789."):

Note that if num[p] is already a string, the str() is not necessary (your original code used int(-1) which is also redundant because -1 is already an int). If it’s a number already, then this whole if statement is unnecessary.

In general, the in operator is the right way to figure out if a thing is in another thing; only use methods like find or index if you need the actual index. The any function combined with a generator expression (for ... in ...) lets you apply that in check a bunch of times to a bunch of different items instead of needing to spell out each individual one.

If this is an XY problem and you’re really trying to figure out if num[p] can or can’t be interpreted as a float, you should instead do:

try:
    n = float(num[p])
    # do whatever
except ValueError:
    # do whatever else
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading