0

I have a returned string from a function such:

"& True  True & True  False & False"

I need to write a function that puts all the elements between & in a list and deletes it, such:

[[True, True], [True, False], [False]] 

How do I do it? thanks in advance!

3
  • results = mystring.split("&") would be a good start. Commented Jan 6, 2021 at 17:37
  • Then for each of the elements of that list you can use split() to split it at whitespace. Then loop over those strings and replace "True" with True and "False" with False Commented Jan 6, 2021 at 17:38
  • Since there are already a lot of answers: [list(map(lambda s: s=='True', entry.split())) for entry in value.split('&') if entry] Commented Jan 6, 2021 at 17:45

5 Answers 5

2

you can use split

 l = "& True  True & True  False & False"
 result = [j.split() for j in l.split('&') if j!='']
 print(result)

output

[['True', 'True'], ['True', 'False'], ['False']]
Sign up to request clarification or add additional context in comments.

Comments

1

With regex:

import re
s = "& True  True & True  False & False"
out = [list(map(eval, i.split())) for i in re.findall("&?([^&]+)&?", s)]

gives

[[True, True], [True, False], [False]]

As it is known, eval is dangerous so if you actually want the boolean values, use ast.literal_eval in place of eval as the safest choice, or you can have a dirty lambda inside like this:

[list(map(lambda x: x == 'True', i.split())) for i in re.findall("&?([^&]+)&?", s)]

3 Comments

eval? Really?
Didn't feel like adding ast.literal_eval for fixed strings.
Let's just mention that eval should never be used with untrusted data. If this string is fixed the answer would be print([[True, True], [True, False], [False]]) ;)
1

and dont forget to cast it to bool:

mystr = "& True  True & True  False & False"
l = [[s == 'True' for s in t.strip().split()] for t in mystr.strip('&').split('&')]
>>> l
[[True, True], [True, False], [False]]

Comments

0

You can use split method of string

yourstring.split("&")

see this , it can be helpfull for you .

https://www.w3schools.com/python/ref_string_split.asp

Comments

0

Another way to do it with filter, map and split,

string = '& True True & True False & False'
required = list(filter(None,map(str.strip, string.split('&'))))
result = [l.split() for l in required]
print(result)

Result:

[['True', 'True'], ['True', 'False'], ['False']]

3 Comments

isn't this over-engineered?
Also, you don't need to convert the map object to list, direct filter over map would work just fine: list(filter(None, map(str.strip, s.split('&'))))
@sahasrara62 Yes, because I like over engineering :P. Thanks for pointing out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.