-1

I want to check for a sub letter so I wrote this code (Python 2.7):

print text
if ('e' or 'E') in text:
    text = "%s"%float(text)
    print text

as suggested here.

text is a variable which changes, curently it has the value: 0E-7

However this doesn't work. When I debug it jumps over the if block.

Why the condition is false?

Community
  • 1
  • 1
SMW
  • 339
  • 1
  • 4
  • 12

3 Answers3

3

What your code is asking is "Is the value ('e' or 'E') in text?" The when you evaluate ('e' or 'E'), you get 'e'. Here's the fix:

if ('e' in text) or ('E' in text):
Joshua R.
  • 111
  • 4
1

('e' or 'E') evaluates to 'e'. So you are testing if 'e' in text: which is not true here since the E in 0E-7 is uppercase.

Here you can see it interactively:

>>> text = '0E-7'                  # note that E is uppercase
>>> ('e' or 'E') in text           # why is this false?
False
>>> ('E' or 'e') in text           # but true here?
True
>>> ('e' or 'E')                   # aha! 'or' returns the first truthy value
'e'
>>> 'e' in text.lower()            # this fixes it
True
>>> any(c in text for c in 'eE')   # another possible fix
True
>>> not set(text).isdisjoint('eE') # yet another way to do it
True
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • ('e' or 'E') evaluates to 'e', since the `or` accepts the first value if it is "truthy" – jcfollower May 25 '16 at 15:53
  • @jcfollower: Yeah, I can't believe I made that error. That's what happens when you get banished to vbscript for months on end, you start inventing semantics that exist in neither language. – Steven Rumbalski May 25 '16 at 16:01
0

('e' or 'E') is a boolean expression, and it is evaluated as 'e'.

My suggestion is:

if any(char in text for char in ('e', 'E')):
    # ...
Jorge Barata
  • 2,227
  • 1
  • 20
  • 26