Skip to content
Sign upLog in
← Back to Community

How to turn String to Boolean in Python

Profile icon
hg0428Hacker

If I have the String "b==True or a<5", how would I evaluate that without the dangers of Eval or Exec?

I do not want to use Eval or Exec, because my program takes the Boolean expression from input.

Answered by Coder100 [earned 5 cycles]
View Answer
Voters
Profile icon
RitaHardeman
Profile icon
hg0428
Comments
hotnewtop
Profile icon
Coder100

Hi! Unfortunately, you wouldn't be able to do this without writing a "language" for it.

Profile icon
hg0428

Thats what I thought, I asked this question to see if any one elese had a better idea.
I have written a "language" for this purpose before, but I dont know where it is.

@Coder100

Profile icon
PattanAhmed

@hg0428
Hi,
You can use bool Function to convert a string into a Boolean Value
Check this code down below and try to fix it in your code in which place you want :)

s = input('Input cat or dog: ') if s== 'cat': bool(s) print(True) elif s== 'dog': bool('') print(False)

As you can see above that I have converted String into a Boolean

If you want to know how it is boolean then, Check in the Print Statement inside If Statement... Normally you have to type "" this, but now without that, it can print the statement without any kind of errors

After that, You can consider it as a Boolean in the next lines of your code!

Hope this helps
Please mark my answer if this helps

Profile icon
hg0428

Bool function will not execute a boolean expression.


@PattanAhmed

Profile icon
PattanAhmed

@hg0428
Oh Ok!

Profile icon
[deleted]
if a<5: a = True else: a = False if b == True or a == True: print("Please mark it as helped(if it helped you)")