3

So I have this data that list of True and False for example

tf = ['True', 'False', 'False']

how can I convert tf to a bool. Once I print(tf[0]) it prints

True

4 Answers 4

4

Use the ast module:

import ast
tf = ['True', 'False', 'False']
print(type(ast.literal_eval(tf[0])))
print(ast.literal_eval(tf[0]))

Result:

<class 'bool'>
True

Ast Documentation

Literal_eval

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

Comments

2

Simply use a dictionary to map the strings and boolean values

tf = ['True', 'False', 'False']
toBool = {'True':True,'False':False}
print(toBool[tf[0]])

Comments

1

You can compare each element of the tf list with True or False

for idx, val in enumerate(tf):
    if val == "True":
        tf[idx] = True
    else:
        tf[idx] = False

1 Comment

tf = [val == 'True' for val in tf]
-1

you can use: eval(tf[0]) for that task.

5 Comments

bool('False') also returns True.
Yeah my mistake. Now I updated. This work
Never use eval() on data!
If I am wrong plz correct me. We do not use eval because it can cause injections from malicious users right? Are there any other reasons. Asking this for just learn.
@YJR Correct. And for me it often makes the code harder to read.

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.