0

if the string is '007w', then when it tries to return '007w' as integer, i want it to return None and print('Cannot be converted). But without using the Try Except ValueError:

import random

def random_converter(x):
    selection = random.randint(1,5)
    if selection == 1:
        return int(x)
    elif selection == 2:
        return float(x)
    elif selection == 3:
        return bool(x)
    elif selection == 4:
        return str(x)
    else:
        return complex(x)


for _ in range(50):
    output = random_converter('007w')
    print(output, type(output))
drleechy
  • 21
  • 3
  • 3
    why don't you want to use try except? – user1558604 Dec 09 '19 at 16:01
  • i would use try-expect but with `random.choice([int, float, bool, str, complex])(x)` – Chris_Rands Dec 09 '19 at 16:07
  • 1
    Does this answer your question? [How do I check if a string is a number (float)?](https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float) – Sayse Dec 09 '19 at 16:07
  • See above comment, specially answer with isdigit() – B. Go Dec 09 '19 at 16:09
  • @user1558604 challenging to find different ways to solve things and get around things the hard way, so in future problems I'll have a more analytical approach – drleechy Dec 09 '19 at 16:11

2 Answers2

5

You can use str.isdigit() to check whether a string in python can be parsed into a number or not. It will return true if all values are digits, and false otherwise.

Note that isdigit() is fairly limited in its ability - it can't handle decimal points or negative numbers. If you're expecting to parse anything more complicated than a positive integer, you may want to consider try/except instead.


def parse(in_str):
  if(in_str.isdigit()):
    return int(in_str)
  else:
    print('Cannot be converted')
    return(None)

print(parse("1234"))
print(parse("007w"))

1234
Cannot be converted
None

Demo

Nick Reed
  • 4,989
  • 4
  • 17
  • 37
4

You can use random.choice for your decider and str.isdigit for checking if x can be converted:

def random_converter(x):
    selection = random.choice([int, float, bool, str, complex])
    if x.isdigit() or selection == bool:
        return selection(x)
    else:
        return None
Jab
  • 26,853
  • 21
  • 75
  • 114