1

I have a string:

my_string = "'T1', 'T2', 'T3', 'T4', True, False"

I would like to convert to a list like this

my_list = ['T1', 'T2', 'T3', True, False]

I've tried to do my_string.split(', ') but it converts the True and False into str, which I don't want.

I could write a function but I feel there is something pythonic and very easy to do this.

What would be the best way to do it ?

pault
  • 41,343
  • 15
  • 107
  • 149
yeye
  • 503
  • 4
  • 19

3 Answers3

1

You can use ast.literal_eval to turn a string representation of a list into a list. To make your string a representation of a list, you need to add opening and closing brackets.

from ast import literal_eval
my_string = "'T1', 'T2', 'T3', 'T4', True, False"
my_list = literal_eval("[" + my_string + "]")
print(my_list)
#['T1', 'T2', 'T3', 'T4', True, False]

You can see the types of the last two elements are bool:

print([type(x) for x in my_list])
#[str, str, str, str, bool, bool]

Update

A neater solution as proposed by @Chris_Rands

my_list = list(literal_eval(my_string))
pault
  • 41,343
  • 15
  • 107
  • 149
  • 2
    `list(literal_eval(my_string))` might be neater – Chris_Rands Jun 05 '19 at 21:03
  • 1
    Your solution works perfectly in the example I've provided, but in my case, I have sometimes only one string " 'T1' " in my main string in which case the list(literal_eval(my_string)) doesn't work for my needs. – yeye Jun 05 '19 at 21:16
0

A quick way to do it, is with list comprehension:

[
  value.strip() if value.strip().startswith("'") else value == 'True' 
  for value in string.split(',')
]

pault answer looks nicer :)

Krukas
  • 657
  • 3
  • 10
  • Thank you as well, a bit longer than Pault's answer as you mentionned, and worked for my needs so I'll stick with his :) – yeye Jun 05 '19 at 20:59
0

So your really close and actually have half of the solution, all you need to do now is iterate over the list and convert the string "True" to the bool True. Below is the full solution:

string = "'T1', 'T2', 'T3', 'T4', True, False"
list = string.split(', ') #Split string into list

number = 0   #create a number so you can track what element of the list you are at

for i in list: #For each item in the list
    if i.upper() == 'TRUE':
        list[number] = True #Replace any 'True' with bool True
        number += 1 #Move number to next item in list
    elif i.upper() == 'FALSE':
        list[number] = False
        number += 1
    else:
        number += 1 #If item is not 'True' or 'False' go to to next item
print(list)

There are more compact and elegant ways of doing this but I've kept it simple so it's easy to understand. The .upper after the i means any way you type True or TRue or TrUe or TRUE etc will be converted to a bool True which the other two solutions won't.

Hope this helps.

Dave748
  • 30
  • 6