String Manipulating and slicing from a list - string

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

Related

How do I properly convert a string to a list

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']]

Convert elements in ONE list to keys and values in a dictionary

I'm looking for a way to convert a list to a dictionary as shown below. Is this possible? Thanks in advance.
list = ["1/a", "2/b", "3/c"]
dict = {"1": "a", "2": "b", "3": "c"}
Of course it is possible.
First, you can split an element of the list with e.split("/"), which will give a list for example splitted = ["1", "a"].
You can assign the first element to the key and the second to the value:
k = splitted[0]
v = splitted[1]
or another way to express that:
k,v = splitted
Then you can iterate over your list to build your dict, so if we wrap this up (you should not call a list list because list is a type and an already existing identifier:
d = {}
for e in elements:
k,v = e.split("/")
d[k] = v
You can also do that in one line with a dict comprehension:
d = {k:v for k,v in [e.split("/") for e in elements]}
Yes you can.
If you want to have everything after the '/' (i.e. 2nd char), you can do:
dict = {c[0]:c[2:] for c in list}
If you want to have everything after the '/' (but may not be the 2nd char), you can do:
dict = {c[0]:c.split('/')[1] for c in list}
It really dependes on the input you have and what output you want
You can do like this.
lista = ["1/a", "2/b", "3/c"]
new_dict = {}
for val in lista:
new_dict.update({val[0]:val[2]})
print(new_dict)
Try this
list = ["1as/aasc", "2sa/bef", "3edc/cadeef"]
dict = {i.split('/')[0]:i.split('/')[1] for i in list}
Answer will be
{'1as': 'aasc', '2sa': 'bef', '3edc': 'cadeef'}
I have given a different test case. Hope this will answer your question.

Is it possible to transform a string into a list, like this: "man1\nman2\nwoman\nman4" into ["man1", "man2", "man4"] in PYTHON

Is it possible to transform a string into a list, like this:
"man1\nman2\nwoman\nman4"
into
["man1", "man2", "man4"]
in python
Yes, you need to use string.split.
>>> x = "man1\nman2\nman3"
>>> x.split('\n')
['man1', 'man2', 'man3']
I got the answer.
in_str = "man1\nman2\nwoman\nman4"
lst = list(in_str.split("\n"))
out = [x for x in lst if re.search(man, x)]
print out
This prints ["man1", "man2", "man4"]

Numpy array into list

I have a numpy array that looks like below:
x = ['11BIT' '4FUNMEDIA' 'ABCDATA' 'ABPL' 'ACAUTOGAZ' 'ADIUVO']
The output should be like this:
x = ['11BIT', '4FUNMEDIA', 'ABCDATA', 'ABPL', 'ACAUTOGAZ', 'ADIUVO']
I tried to use x.tolist() but it didn't help. Basically I need a coma between values. Anyone could help ?
Thanks All
"A comma between values" as in a string?
",".join(x)
if you want a true list:
x = list(x)
or
x = [i for i in x]
should do the trick

How to modify each entry in the list by converting it to a numeric value?

I'm trying to write function called toNumbers based on the following specifications:
-toNumbers modifies each entry in the list by converting it to a numeric value.
-Call toNumbers function to convert each entry in the list to numeric form.
- Display the original and converted lists in your main function, not in toNumbers
for i in (toNumbers(myList)):
myList[i] = myList [i] * (1+rate)
def main():
myList = ['5','-2','3.5','-4.5']
print(myList)
main()
However, I'm not sure what function to use in order to modify my list.
Thanks!
(I'm using Python 3.5)
rate = 0.5
input_list = ['5','-2','3.5','-4.5']
output_list = [float(item)*(1+rate) for item in input_list]
print(output_list)
Your main will look like this:
if __name__=='__main__':
new_list = [toNumbers(num) for num in myList]
print(new_list, myList)
it creates new_list by calling toNumbers on each value in the list, than returns a list of those values
then it prints both lists all in main

Resources