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))
5
  • 3
    why don't you want to use try except? Commented Dec 9, 2019 at 16:01
  • i would use try-expect but with random.choice([int, float, bool, str, complex])(x) Commented Dec 9, 2019 at 16:07
  • 1
    Does this answer your question? How do I check if a string is a number (float)? Commented Dec 9, 2019 at 16:07
  • See above comment, specially answer with isdigit() Commented Dec 9, 2019 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 Commented Dec 9, 2019 at 16:11

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

The same still applies for str and float for example
Now that's a pythonic answer. Almost feels taboo to think you can cast to any value in a string, +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.