Converting A List With Python - python
I have a large list of names which is in this format
list1 = ["apple", "orange", "banana", "pine-apple"]
And I want it in this format
list1 = ["'apple'", "'orange'", "'banana'", "'pine-apple'"]
Basically, I want to add punctuation marks to every single word in the list
but since the list is too large, I can't do it manually.
So is there any python function or way to do this task. Thank You.
The names in python are already strings enclosed in the quotes like you have shown here. I am supposing you want to wrap the string with specific quote to look this '"apple"' or "'apple'". To do so, you should use the following snippet
q = "'" # this will be wrapped around the string
list1 = ['apple','orange','banana','pine-apple']
list1 = [q+x+q for x in list1]
For reference, the syntax I have used in last line is known as list comprehension
According to latest comment posted by #xdhmoore
If you are using vim/nano (linux/macos) or notepad(windows), then i would rather suggest you to use IDLE python (shipped with python setup)
Str function is the built in function to convert a value into string.
You can run this code;
For i in range(len(list1)):
new = str(list1[i])
list1.remove(list[i])
list1.append(new)
Using for loop to process each line, two ways to go
text = "list1 = [apple,orange,banana,pine-apple]"
start = text.find('[')+1
stop = text.find(']')
lst = text[start:stop].split(',') # ['apple', 'orange', 'banana', 'pine-apple']
new_lst = [f'"{item}"' for item in lst] # ['"apple"', '"orange"', '"banana"', '"pine-apple"']
new_text1 = text[:start]+','.join(new_lst)+text[stop:] # 'list1 = ["apple","orange","banana","pine-apple"]'
text = "list1 = [apple,orange,banana,pine-apple]"
new_text2 = text.replace('[', '["').replace(']', '"]').replace(',', '","')
Related
How to print specific data from JSON file lists in a line break layout?
Take this example: "something": { "random": 0, "bag": { "papers": 0, "pencils": 0 }, "PAINT": { "COLORS": [ "A WHITE", "B MAPLE", "B LOTUS", "A OLIVE" ], "CANS": [ "SOMETHING" ] } Ignore everything and focus on the COLORS list in the PAINT dictionary... I want to print all colors that have the color A before them, as a code. In other words I want to print "A WHITE" and "A OLIVE". Here's what happens when I do this: with open("somethings.json", "r") as f: data = json.load(f) print(data["something"]["PAINT"]["COLORS"]) This is the output: ["A WHITE", "B MAPLE", "B LOTUS", "A OLIVE"] but like I said, I do not want that... I want only A colors to be printed... I also do not want THIS: ["A WHITE", "A OLIVE"] the output that I really want (which is quite specific) is this: OLIVE WHITE With line breaks (optional: AND in alphabetical order) that is the output that I want. So how can I print this output? is it possible without using any 'for' loops? This is a very specific question, would appreciate some help. Thanks -
Try this code: with open("somethings.json", "r") as f: data = json.load(f) a_colors = [color for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")] colors = [a_color.replace("A ", "") for a_color in a_colors] print(colors) How it works Opens and loads the JSON data. Uses a list comprehension to filter only entries that start with "A ". The .startswith() method of a string returns a boolean value, True if the first few characters of the string are, in fact, the characters passed as an argument, and False otherwise. Uses another list comprehension to get the string without the "A " for each string in the list created in step 2. Replaces the "A " with an empty string, which is a hacky way of deleting part of a string using the .replace() method. It can be done without list comprehensions using a for loop as well See code below: with open("somethings.json", "r") as f: data = json.load(f) a_colors = [] for color in data["something"]["PAINT"]["COLORS"]: if color.startswith("A "): color_without_a = color.replace("A ", "") a_colors.append(color_without_a) print(a_colors) This solution uses a for loop rather than a list comprehension but is otherwise the same. (If you are confused, see below for a solution which is an exact replica of the list comprehension one but implemented with for loops). If you are interested, here is a lengthier solution more similar to the list comprehension one, using for loops: with open("somethings.json", "r") as f: data = json.load(f) a_colors = [] for color in data["something"]["PAINT"]["COLORS"]: if color.startswith("A "): a_colors.append(color) colors = [] for a_color in a_colors: colors.append(a_color.replace("A ", "")) print(colors) To sort alphabetically, use the sorted() function, like this for the list comprehension solution and the second for loop solution: sorted_list = sorted(colors) print(sorted_list) For the first for loop solution: sorted_list = sorted(a_colors) print(sorted_list) Recommended reading Python Data Structures documentation Examples of list comprehensions for practice Beginner's list comprehension tutorial Filtering lists in Python Other helpful resources List slicing Sorting Lists I strongly recommend watching this video as well: Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
Well, you can't really don't use a for-loop, you need to iterate over all elements in your COLORS array. So, what you want to do is: Iterate over all elements Check if the first character of each element (e.g. A WHITE) is the desired character (e.g. A) either print the output directly or store it in list without the A (notice the space) So: with open("somethings.json", "r") as f: data = json.load(f) colors = data["something"]["PAINT"]["COLORS"] best_colors = [] for color in colors: if color[0] == "A": # or any character you want; CASE SENSITIVE! best_colors.append(color[2:]) # this adds the color without the A and the space to the list # Optionally: Sort alphabetically sorted_colors = sorted(best_colors) Additional resources to help you to understand the code better: List slicing Sorting Lists
Based on Unix Doughnut's answer: # Read JSON File with open("file_name.json", "r") as f: data = json.load(f) # Sort the selected elements starting with A without the leading A colors = sorted([color.replace("A ", "") for color in data["something"]["PAINT"]["COLORS"] if color.startswith("A ")]) # Print list elements separated by line break ( without for loop ) print(*colors, sep='\n')`
Remove Prefixes From a String
What's a cute way to do this in python? Say we have a list of strings: clean_be clean_be_al clean_fish_po clean_po and we want the output to be: be be_al fish_po po
Another approach which will work for all scenarios: import re data = ['clean_be', 'clean_be_al', 'clean_fish_po', 'clean_po', 'clean_a', 'clean_clean', 'clean_clean_1'] for item in data: item = re.sub('^clean_', '', item) print (item) Output: be be_al fish_po po a clean clean_1
Here is a possible solution that works with any prefix: prefix = 'clean_' result = [s[len(prefix):] if s.startswith(prefix) else s for s in lst]
You've merely provided minimal information on what you're trying to achieve, but the desired output for the 4 given inputs can be created via the following function: def func(string): return "_".join(string.split("_")[1:])
you can do this: strlist = ['clean_be','clean_be_al','clean_fish_po','clean_po'] def func(myList:list, start:str): ret = [] for element in myList: ret.append(element.lstrip(start)) return ret print(func(strlist, 'clean_')) I hope, it was useful, Nohab
There are many ways to do based on what you have provided. Apart from the above answers, you can do in this way too: string = 'clean_be_al' string = string.replace('clean_','',1) This would remove the first occurrence of clean_ in the string. Also if the first word is guaranteed to be 'clean', then you can try in this way too: string = 'clean_be_al' print(string[6:])
You can use lstrip to remove a prefix and rstrip to remove a suffix line = "clean_be" print(line.lstrip("clean_")) Drawback: lstrip([chars]) The [chars] argument is not a prefix; rather, all combinations of its values are stripped.
Question about String operations in Python
I am new to Python, and was practising File Operations. I have written this program: myfile = open('test3.txt', 'w+') myfile.writelines(['Doctor', 'Subramanian', 'Swamy', 'Virat', 'Hindustan', 'Sangam']) which outputs the following: DoctorSubramanianSwamyViratHindustanSangam. How do I add spaces in between items of the list in the final output such that the final output is Doctor Subramanian Swamy Virat Hindustan Sangam?
Based on what I understood from your question, you wish to add spaces between elements of the list in the final output. One possible solution is: myfile = open('test3.txt', 'w+') list = ['Doctor', 'Subramanian', 'Swamy', 'Virat', 'Hindustan', 'Sangam'] for l in list: myfile.write(l+' ') In particular, this line myfile.write(l+' ') will add a space after writing every element.
You could try stripping it using the same .strip() method? value = "'" list1 = [] for item in list2: list1.append(item.strip("{0}".format(value))) try it and let me know
How to turn a list containing strings into a list containing integers (Python)
I am optimizing PyRay (https://github.com/oscr/PyRay) to be a usable Python ray-casting engine, and I am working on a feature that takes a text file and turns it into a list (PyRay uses as a map). But when I use the file as a list, it turns the contents into strings, therefore not usable by PyRay. So my question is: How do I convert a list of strings into integers? Here is my code so far. (I commented the actual code so I can test this) print("What map file to open?") mapopen = input(">") mapload = open(mapopen, "r") worldMap = [line.split(',') for line in mapload.readlines()] print(worldMap) The map file: 1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2, 2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,0,2,0,0,3,0,0,0,0,0,0,0,2,3,2,3,0,0,2, 2,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2, 2,3,1,0,0,2,0,0,0,2,3,2,0,0,0,0,0,0,0,1, 1,0,0,0,0,0,0,0,0,1,0,1,0,0,1,2,0,0,0,2, 2,0,0,0,0,0,0,0,0,2,0,2,0,0,2,1,0,0,0,1, 1,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,0,0,2, 2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 1,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2, 2,0,3,0,0,2,0,0,0,0,0,0,0,2,3,2,1,2,0,1, 1,0,0,0,0,3,0,0,0,0,0,0,0,1,0,0,2,0,0,2, 2,3,1,0,0,2,0,0,2,1,3,2,0,2,0,0,3,0,3,1, 1,0,0,0,0,0,0,0,0,3,0,0,0,1,0,0,2,0,0,2, 2,0,0,0,0,0,0,0,0,2,0,0,0,2,3,0,1,2,0,1, 1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,3,0,2, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,1, 2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1, Please help me, I have been searching all about and I can't find anything.
try this: Did you want a list of lists? or just one big list? with open(filename, "r") as txtr: data = txtr.read() data = txtr.split("/n") # split into list of strings data = [ list(map(int, x.split(","))) for x in data] fourth line splits string into list by removing comma, then appliea int() on each element then turns it into a list. It does this for every element in data. I hope it helps. Here is for just one large list. with open(filename, "r") as txtr: data = txtr.readlines() # remove empty lines in your file! data = ",".join(data) # turns it into a large string data = data.split(",") # now you have a list of strings data = list(map(int, data)) # applies int() to each element in data.
Look into the map built-in function in python. L=['1', '2', '3'] map = map(int, L) for el in map: print(el) >>> 1 ... 2 ... 3
As per you question, please find below a way you can change list of strings to list of integers (or integers if you use list index to get the integer value). Hope this helps. myStrList = ["1","2","\n","3"] global myNewIntList myNewIntList = [] for x in myStrList: if(x != "\n"): y = int(x) myNewIntList.append(y) print(myNewIntList)
Python Joining List and adding and removing characters
I have a list i need to .join as string and append characters my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2'] my_list.append(')"') my_list.insert(0,'"(') hostman = '|'.join('{0}'.format(w) for w in my_list) #my_list.pop() print(hostman) print(my_list) My output = "(|3.3.3.3|2.2.2.3|2.2.2.2|)" I need the output to be = "(3.3.3.3|2.2.2.3|2.2.2.2)" how can i strip the first and last | from the string
You are making it harder than it needs to be. You can just use join() directly with the list: my_list = ['3.3.3.3', '2.2.2.3', '2.2.2.2'] s = '"(' + '|'.join(my_list) + ')"' # s is "(3.3.3.3|2.2.2.3|2.2.2.2)" # with quotes as part of the string or if you prefer format: s = '"({})"'.format('|'.join(my_list))
Try this : hostman = "("+"|".join(my_list)+")" OUTPUT : '(3.3.3.3|2.2.2.3|2.2.2.2)'