How do I properly convert a string to a list - python-3.x

I have a function that returns a message as a string as follows:
l = ['["sure","kkk"]', '["sure","ii"]']
I have tried to remove the "'" character through an iteration but its not working for me.
This is my code:
print([item.replace('\'["','"').replace('"]\'','"') for item in l])
Is there a better way to do this since I want the results as this:
l = [["sure","kkk"], ["sure","ii"]]

Those are JSON encoded strings, so you should use the json API for that and not try to parse it "yourself":
import json
l = ['["sure","kkk"]', '["sure","ii"]']
l = [json.loads(s) for s in l]
print(l) # [['sure', 'kkk'], ['sure', 'ii']]
Can also be achieved with map instead of list comprehension:
l = list(map(json.loads, l))

Alternatively, you can also use ast.literal_eval (see the docs) as follows:
import ast
l = ['["sure","kkk"]', '["sure","ii"]']
l = [ast.literal_eval(s) for s in l]
print(l) # [['sure', 'kkk'], ['sure', 'ii']]

Related

How To Generate A List Of Possible Combination From A Set Dictionary

I'm a beginner coder, I have the code below
def PossibleNum(List):
DefaultSymbol = '%'
NumDict = ["0","1","2","3","4","5","6","7","8","9"]
FinishList = []
for Item in List:
for i in range(len(NumDict)):
_item = Item.replace(DefaultSymbol,NumDict[i])
FinishList.append(_item)
return FinishList
List = ["AAAA%%","BBB%%%","CC%%C%"]
print (PossibleNum(List))
I'm trying to get every possible combination from NumDict by Replacing each of "%" into every possible NumDict
Wanted Output : [AAAA00,AAAA01,AAAA02,AAAA03....,AAAA99]
Current Output : [AAAA11,AAAA22,AAAA33,AAAA,44,AAAA55,AAAA66]
You can use str.replace with count parameter set to 1. To obtain the combinations, I used str.format method.
For example:
lst = ["AAAA%%","BBB%%%","CC%%C%"]
output = []
for i in lst:
n = i.count('%')
backup = i
for v in range(10**n):
i = backup
for ch in '{:0{n}}'.format(v, n=n):
i = i.replace('%', ch, 1)
output.append(i)
# pretty print:
from pprint import pprint
pprint(output)
Prints:
['AAAA00',
'AAAA01',
'AAAA02',
'AAAA03',
...all the way to:
'CC99C5',
'CC99C6',
'CC99C7',
'CC99C8',
'CC99C9']
An option using itertools.product to get all the possible inserts:
import itertools
l = ["AAAA%%","BBB%%%","CC%%C%"]
DefaultSymbol = '%'
NumDict = ["0","1","2","3","4","5","6","7","8","9"]
out = []
for s in l:
n = s.count(DefaultSymbol)
prod = itertools.product(NumDict, repeat=n)
for p in prod:
tmp = s
for i in p:
tmp = tmp.replace(DefaultSymbol, i, 1)
out.append(tmp)
Pretty straight forward; for each input list element get the number of replacements (count of '%'), calculate all possible elements to insert using itertools.product, then iterate over all these elements (for p in prod) and do the replacements, one at a time (for i in p, with replace count set to 1).

reading inversed a dictionary python

I have this code in python 3.7
dictionnaire = {'a':'url1', 'b':'url2', 'c': 'url3'}
for key, value in dictionnaire.items():
print(key + ' ' + value)
the result is :
a url1
b url2
c url3
but i want this result
c url3
b url2
a url1
Thank you very much for your help
You can convert the dictionary items to a list, in order to reverse it. You've two ways:
Using reversed function:
for k,v in reversed(list(dictionnaire.items())):
print(k,v)
Using reverse on the list object:
l = list(dictionnaire.items()).reverse()
for k,v in l:
print(k,v)
One way to do it is by extracting keys from dictionary and reverse it.
keys = list(dictionnaire.keys())
Then use this list in reverse order to get the desired output.
for k in keys[::-1]:
print(k, dictionnaire[k])
convert to list
dic_list = list(dictionnaire.items())
reverse
dic_list.reverse()
read
for k, v in dic_list:
print(k + ' ' + v)

How to split the sinhala word by specific character of the word in python. I tried with using the length of the word. Is there any other methods?

I used this. But it is not applicable for all the cases.
def splitword(verb_list):
split = -((-len(verb_list))//2)
return verb_list[:split], verb_list[split:]
print(verb_list)
If you want to remove a specific word from each string in a list you can use the str.replace() method in a list comprehension:
l = ['බලනවා', 'නටනවා']
l = [s.replace('නවා', '') for s in l]
l would become:
['බල', 'නට']

How to use re.compile within a for loop to extract substring indices

I have a list of data from which I need to extract the indices of some strings within that list:
str=['cat','monkey']
list=['a cat','a dog','a cow','a lot of monkeys']
I've been using re.compile to match (even partial match) individual elements of the str list to the list:
regex=re.compile(".*(monkey).*")
b=[m.group(0) for l in list for m in [regex.search(l)] if m]
>>> list.index(b[0])
3
However, when I try to iterate over the str list to find the indices of those elements, I obtain empty lists:
>>> for i in str:
... regex=re.compile(".*(i).*")
... b=[m.group(0) for l in list for m in [regex.search(l)] if m]
... print(b)
...
[]
[]
I imagine that the problem is with regex=re.compile(".*(i).*"), but I don't know how to pass the ith element as a string.
Any suggestion is very welcome, thanks!!
It looks like you need to use string formatting.
for i in str:
match_pattern = ".*({}).*".format(i)
regex = re.compile(match_pattern)
b = [m.group(0) for l in list for m in [regex.search(l)] if m]
print(b)

String Manipulating and slicing from a list

import os
a = ['docs-assets', 'ico', 'favicon.png']
for item in range(len(a)):
z = os.path.join("sample",a[item])
print(z)
Results:
sample\docs-assets
sample\ico
sample\favicon.png
Can you tell me how i can join each item in the "a" list using os.path.join() so that the result would be:
sample\docs-assets\ico\favicon.png
Thanks
Like so:
os.path.join('sample', *a)
You can do it as:
s = 'sample\\'+'\\'.join(a)
>>> print s
sample\docs-assets\ico\favicon.png
DEMO

Resources