Question about String operations in Python - 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
Related
Efficiently create list of list of list with varying amount of input
I have a .txt file with floating point numbers inside. This file always contains an even number of values which need to be formatted as follows: [[[a,b],[c,d],[e,f]]] The values always need to be in pairs of two. Even when there are less or more values: [[[a,b], ... [y,z]]] So it needs to go from this: 3.31497114423 50.803721015, 7.09205325687 50.803721015, 7.09205325687 53.5104033474, 3.31497114423 53.5104033474, 3.31497114423 50.803721015 To this: [[[3.31497114423,50.803721015],[7.09205325687,50.803721015],[7.09205325687,53.5104033474],[3.31497114423,53.5104033474],[3.31497114423,50.803721015]]] I have the feeling this can be done fairly easy and efficiƫnt. The code I have so far works, but is far from efficient... with open(filename) as f: for line in f: footprint = line.strip() splitted = footprint.split(' ') list_str = [] for coordinate in splitted: list_str.append(coordinate.replace(',', '')) list_floats = [float(x) for x in list_str] footprint = [list_floats[x:x+2] for x in range(0, len(list_floats), 2)] return [footprint] Any help is greatly appreciated!
The split function is very useful in scenarios such as these. with open(filename) as f: # Format the string of numbers into a list seperated by commas new_list = f.read().split(", ") # For every element in this list, make it a list seperated by space # Also convert the strings into floats for i in range(len(new_list)): new_list[i] = list(map(float, new_list[i].split(" "))) new_list = [new_list] The first split converts the code from this 3.31497114423 50.803721015, 7.09205325687 50.803721015, 7.09205325687 53.5104033474, 3.31497114423 53.5104033474, 3.31497114423 50.803721015 To this ['3.31497114423 50.803721015', '7.09205325687 50.803721015', '7.09205325687 53.5104033474', '3.31497114423 53.5104033474', '3.31497114423 50.803721015'] The second split converts that to this [['3.31497114423', '50.803721015'], ['7.09205325687', '50.803721015'], ['7.09205325687', 53.5104033474'], ['3.31497114423', '53.5104033474'], ['3.31497114423', '50.803721015']] Then the mapping of the float function converts it to this (the list converts the map object to a list object) [[3.31497114423, 50.803721015], [7.09205325687, 50.803721015], [7.09205325687, 53.5104033474], [3.31497114423, 53.5104033474], [3.31497114423, 50.803721015]] The last brackets place the whole thing into another list [[[3.31497114423, 50.803721015], [7.09205325687, 50.803721015], [7.09205325687, 53.5104033474], [3.31497114423, 53.5104033474], [3.31497114423, 50.803721015]]]
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)
How to remove the stuff lists add when writing to textfiles
I need to write a list to a text file named accounts.txt in the following format: kieranc,conyers,asdsd,pop ethand,day,sadads,dubstep However, it ends up like the following with brackets: ['kieranc', 'conyers', 'asdsd', 'pop\n']['ethand', 'day', 'sadads', 'dubstep'] Here is my code (accreplace is a list): accreplace = [['kieranc', 'conyers', 'asdsd', 'pop\n'],['ethand', 'day', 'sadads', 'dubstep']] acc = open("accounts.txt", "w") for x in accreplace: acc.write(str(x))
Since each element in accreplace is a list, str(x) doesn't help. It just adds quotes around it. To print the list in proper format use the code below: for x in accreplace: acc.write(",".join([str(l) for l in x])) This will convert the list items into a string.
Python len not working
In the code below, I am trying to use len(list) to count the number of strings in an array in each of the tags variables from the while loop. When i did a sample list parameter on the bottom, list2, it printed 5 which works, but when i did it with my real data,it was counting the characters in the array, not the number of strings. I need help figuring out why that is and i am new to python so the simplest way possible please! #!/usr/bin/python import json import csv from pprint import pprint with open('data.json') as data_file: data = json.load(data_file) #pprint(data) # calc number of alert records in json file x = len(data['alerts']) count = 0 while (count < x): tags = str(data['alerts'][count] ['tags']).replace("u\"","\"").replace("u\'","\'") list = "[" + tags.strip('[]') + "]" print list print len(list) count=count+1 list2 = ['redi', 'asd', 'rrr', 'www', 'qqq'] print len(list2)
Your list construction list = "[" + tags.strip('[]') + "]" creates a string, not a list. So yes, len works, it counts the characters in your string. Your tags construction looks a bit off, you have a dictionary of data (data['alerts']) which you then convert to string, and strip of the '[]'. Why don't use just get the value itself? Also list is a horrible name for your variable. This possible clashes with internal values.
list = "[" + tags.strip('[]') + "]" print list print len(list) Ironically, list is a string, not a list. That's why calling len on it "was counting the characters in the array"
you need to make sure that your variable is a list rather than a str, try: print(type(yourList)) if it shows that it is a str, then try this: len(list[yourList) hope this answers your question and when you want to establish a list variable, try this: myList = [] for blah in blahblah: myList.append(blah) I think these definitely solved your problem, so I hope you noticed this part.
How do you split a single python list element into several independent list elements?
I have a .txt file that reads exactly like this: 0,Hello,01,Cooking,02,Biking,13,My Hawaii Vacation,14,Freezing weather in Iowa,0 The code I have so far is: a = open('wiki.txt','r') ar = a.readlines() biglistA = map(lambda each:each.strip('\n'), ar) Which gives me output of: ['0,Hello,0', '1,Cooking,0', '2,Biking,1', '3,My Hawaii Vacation,1', '4,Freezing weather in Iowa,0'] I need to get this to look like: [['0','Hello','0'], ['1','Cooking','0'], ['2','Biking','1'], ['3','My Hawaii Vacation','1'], ['4','Freezing weather in Iowa','0']] The final product needs to be a nested list with each element being referenced, i.e: print newlist[1][1] 'Cooking' That is the desired output. If anyone can help it would be greatly appreciated!
It looks to me like you need something like: with open('wiki.txt') as fin: bigListA = [ line.strip().split(',') for line in fin ]
A strange requirement. I guess a regex would be the best bet: import re with open('wiki.txt') as f: s = f.read() newlist = [triple.split(',') for triple in re.findall(r'\d,.*?,\d', s)] Or, continuing on from where you were at already, just apply a list comprehension like: newlist = [x.split(',') for x in biglistA]