If you literally want to raise an exception only on the empty string, you'll need to do that manually:
try:
user_input = input() # raw_input in Python 2.x
if not user_input:
raise ValueError('empty string')
except ValueError as e:
print(e)
But that "integer input" part of the comment makes me think what you really want is to raise an exception on anything other than an integer, including but not limited to the empty string.
If so, open up your interactive interpreter and see what happens when you type things like int('2'), int('abc'), int(''), etc., and the answer should be pretty obvious.
But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input() before the try, and check whether user_input is empty within the except. (You put if statements inside except handlers all the time in real code, e.g., to distinguish an OSError with an EINTR errno from one with a different errno.)
If you literally want to raise an exception only on the empty string, you'll need to do that manually:
try:
user_input = input() # raw_input in Python 2.x
if not user_input:
raise ValueError('empty string')
except ValueError as e:
print(e)
But that "integer input" part of the comment makes me think what you really want is to raise an exception on anything other than an integer, including but not limited to the empty string.
If so, open up your interactive interpreter and see what happens when you type things like int('2'), int('abc'), int(''), etc., and the answer should be pretty obvious.
But then how do you distinguish an empty string from something different? Simple: Just do the user_input = input() before the try, and check whether user_input is empty within the except. (You put if statements inside except handlers all the time in real code, e.g., to distinguish an OSError with an EINTR errno from one with a different errno.)
try:
input = raw_input('input: ')
if int(input):
......
except ValueError:
if not input:
raise ValueError('empty string')
else:
raise ValueError('not int')
try this, both empty string and non-int can be detected. Next time, be specific of the question.
.Empty string comprehension?
How to check if the string is empty in Python? - Stack Overflow
Python not recognizing an empty string ('') as an empty string
exception - MemoryError's message as str is empty in Python - Stack Overflow
This means the exception has no message attached. Print the exception type:
print repr(e)
You may also want to print the traceback:
import traceback
# ...
except BaseException as e:
traceback.print_exc()
You want to avoid catching BaseException however, this is no better than a blanket except: statement. Catch more specific exceptions instead.
The following produces a blank line of output:
try:
raise Exception()
except BaseException, e:
print str(e)
Use repr(e) to see what the exception is that was raised.
Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
From PEP 8, in the “Programming Recommendations” section:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
So you should use:
if not some_string:
or:
if some_string:
Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.
How come Python is recognizing an empty string ('') (two single quotes not a double quote) as something other than that? type() returns <type 'str'>, repr() returns repr: '', len() returns len: 0
Source python file: https://pastebin.com/kDxYSpwJ
the three source data files:
-
https://pastebin.com/TyVh0Njd
-
https://pastebin.com/2gGBDdP4
-
https://pastebin.com/02yTymJn
The issue in the code starts in the for loop on line 281.
The below is the output of a section of code that I'm running into problems with. I have a dictionary of products (in this case, product '00835K') and each product has multiple items, seven of which are potential components that make up that product (A1 - A7)
I'm using the comp dictionary to iterate through the different components of all the products, ex: 'comp_prod_%s' % comp[comp_index], printing out the keys and values of each one, then checking if each one is an empty string or not. If not, append that value to a dict called dest_prod.
In the section containing the seven component keys (ac2_products['00835K']['comp_prod_A1]...) and the component A4 is listed as an empty string '' but when the check comes to seeing if that value is not equal to '', it fails assuming that '' != ''
Why would Python be assuming/treating this value, that is clearly an empty string as if it weren't?
comp = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7'] 00835K ac2_products['00835K']['comp_prod_A1'] = '000804' ac2_products['00835K']['comp_prod_A2'] = '000808' ac2_products['00835K']['comp_prod_A3'] = '000850' ac2_products['00835K']['comp_prod_A4'] = '' ac2_products['00835K']['comp_prod_A5'] = '' ac2_products['00835K']['comp_prod_A6'] = '' ac2_products['00835K']['comp_prod_A7'] = '' ac2_products['00835K']['comp_prod_A1'], comp_index: 0 ac2_products['00835K']['comp_prod_A1'] != '' (000804) 1: Appended 000804 to 'dest_prod' and 08300000 'dest_pct' ac2_products['00835K']['comp_prod_A2'], comp_index: 1 ac2_products['00835K']['comp_prod_A2'] != '' (000808) 1: Appended 000808 to 'dest_prod' and 01100000 'dest_pct' ac2_products['00835K']['comp_prod_A3'], comp_index: 2 ac2_products['00835K']['comp_prod_A3'] != '' (000850) 1: Appended 000850 to 'dest_prod' and 00500000 'dest_pct' ac2_products['00835K']['comp_prod_A4'], comp_index: 3 ac2_products['00835K']['comp_prod_A4'] != '' ()
So you probably want to print the name of the exception class:
try:
np.arange(1e10)
except Exception as e: #not catch...
print(str(e.__class__.__name__))
print("Catched!")
Using str(e) only prints the "message" of the exception, which in your case was empty.
Note that you can obtain the arguments passed to the exception constructor via the args attribute:
In [4]: try:
...: raise ValueError(1,2,3)
...: except ValueError as e:
...: print('arguments:', e.args)
arguments: (1, 2, 3)
When call str(e) it returns the message of the Exception. Take an example -
NameError: name 'a' is not defined
^ ^
name message
The part before : is the name of the exception, whereas the part after it is the message (arguments).
In the case of MemoryError , as you can see in your example -
MemoryError:
does not have an error message , only the name of the exception , hence you get the empty string.
I am not sure if there are other Exceptions that do not have an exception, but I believe it would be very rare to find such exceptions. Maybe you can print both the exception's name as well as the message , if you really want to take care of the MemoryError (and maybe other such rare exceptions without messages) , something like -
print(type(e).__name__ , ':', str(e))