Other than try and except

Asked 2 months ago, Updated 2 months ago, 4 views

As explained, I wrote the following actions for input like "occasional numbers, occasional strings only", but I heard that throwing anything in try and exception is not a good idea.

How do I sort variables a without relying on try and exception when I do the following?I hope we can get your advice.

Current State Code:

a="Basically, there are numbers, but sometimes strings that do not contain numbers"
b = 0

try:
    b = int(a)
    # a numerical action
except:
    # What to do if it was a string
    pass

python exception

2022-09-30 14:25

3 Answers

Although There is a build-in or more Pythonic way to try to parse a string to an integer in StackOverflow, it is recommended that you use the exception mechanism honestly.except indicates that the value conversion failed.StopIterationException is used to stop repetitive looping.

See also the external article Best Practices for Throwing Exceptions in Python

:


2022-09-30 14:25

Judging from the question, I felt that the purpose was to determine whether variable a is a string or not.
In this case, 。isinstance で can be used to determine if it is a string or an integer.
For example, how about this?

if isinstance(a,str):
  # What to do with a string is a string?
elif isinstance(a, int):
  # integer processing
  b = a
else:
  # Other types of treatment
  print("Invalid value.")


2022-09-30 14:25

If a is a string with no sign (+) before it and no spaces before or after it, what about isdecimal?

a="Basically, there are numbers, but sometimes strings that do not contain numbers"
b = 0

if a.isdecimal():
    b = int(a)
    # a numerical action
else:
    # What to do if it was a string
    pass

int accepts a surprisingly wide range of arguments, so if the above doesn't work, try would be fine.


2022-09-30 14:25

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.