3

How can I replace "True" with the boolean True or 1?

mylist = ["Saturday", "True"]

I've tried replace, but get the error:

TypeError: replace() argument 2 must be str, not bool

Thanks in advance!

dani herrera
  • 48,760
  • 8
  • 117
  • 177
fashioncoder
  • 79
  • 2
  • 8

1 Answers1

6

Using list comprehension:

result = [ True if x == "True" else x for x in mylist  ]

Edited due OP comment

You can use a dictionary to transform some values:

>>> changes = { "True": True,
...             "False": False,
...             "Lemon": "Gin Lemon"
...           }
>>> 
>>> mylist = ["Saturday", "True", "False", "Lemon", "Others" ]
>>> 
>>> [ changes.get( x, x ) for x in mylist ]

['Saturday', True, False, 'Gin Lemon', 'Others']

The tip is to use python dictionary get method with a default value:

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

dani herrera
  • 48,760
  • 8
  • 117
  • 177