How to print array as specific format? - python

I have an array formatted like this:
[-22.99253267 -83.23210952 77.71126322 43.99377722 -41.75731176 89.02862477]
I would like to print this array to receive this result
[-22.992 -83.232 77.711 43.993 -41.757 89.028]
I know It will be a similar result if I use np.set_printoptions(precision=3), but I would like to know how to receive this result using 9.3f.

To print the data in column :
for data in x:
print '{:9.3f}'.format(data)
or
To print the data in row :
(don't forget import sys)
for data in x:
sys.stdout.write('{:9.3f}'.format(data))

Using String.format()
list = [-22.99253267, -83.23210952, 77.71126322, 43.99377722, -41.75731176, 89.02862477]
for numbers in list :
print('{:9.3f}'.format(data))
I receive the output
-22.993
-83.232
77.711
43.994
-41.757
89.029
EDIT
Following OP's comment, here's an update which would append all elements into a list.
y = []
list = [-22.99253267, -83.23210952, 77.71126322, 43.99377722, -41.75731176, 89.02862477]
for numbers in list:
x = '{:9.3f}'.format(data)
y.append(x)
print(y)
Output
[' -22.993', ' -83.232', ' 77.711', ' 43.994', ' -41.757', ' 89.029']

Related

extract value information from python string

I have a string output and I would like to extract the str_data out. That is the value in str_data. Currently I'm using the below code but I think it can be improved on. The below code does not work well with str_data=[''] and str_data=['L'm'] as it return list/index out of range error. str_data contains language information, so it could be empty or contain words like it's. Anyway to improve this? Thanks
right = result.split("str_data=['")[1]
final = right.split("'], extra='")[0]
Example 1:
result = TensorSet(tensors={'result': Tensor(shape=['5'], str_data=['ขอคุยด้วยหน่อย'], extra={})}, extra={}
Example 2:
result = TensorSet(tensors={'result': Tensor(shape=['102'], str_data=[''], extra={})}, extra={}
Example 3:
result = TensorSet(tensors={'result': Tensor(shape=[], str_data=['L'm'], extra={})}, extra={}
I would like to extract out:
example_1_result = 'ขอคุยด้วยหน่อย'
example_2_result = ''
example_3_result = 'L'm'
Assuming TensorFlow(...) is a string, that will always be formatted with the same arguments, then something like this will work:
final = result.split(",")[1].split("str_data=")[1].replace("[","").replace("]","")
Here's a breakdown:
Example input:
result = "TensorSet(tensors={'result': Tensor(shape=['5'], str_data=['ขอคุยด้วยหน่อย'], extra={})}, extra={})"
>>> result.split(",")[1]
" str_data=['ขอคุยด้วยหน่อย']"
>>> data = result.split(",")[1]
>>> data.split("str_data=")[1]
"['ขอคุยด้วยหน่อย']"
>>> content = data.split("str_data=")[1]
>>> content.replace("[","").replace("]","")
"'ขอคุยด้วยหน่อย'"
>>> final = content.replace("[","").replace("]","")
>>> final
"'ขอคุยด้วยหน่อย'"

Concatenate Python string within list

I ve some problem to concatenate a string with my list
I have some list like this :
my_device_list = ['Iphone', 'Samsung', 'Nokia','MI']
I want to join with the list so that i have output like this in a combined string within quotes as seen below:
combinedString = (Device_ID="Iphone" OR Device_ID="Samsung" OR Device_ID="Nokia" OR Device_ID="MI")
How would we concatenate string and those list together to a combined string?
I am trying like this and can add some string at the start but again getting them inside quotes each value converted back to string from list is little tricky and not working
my_device_list = ['Iphone', 'Samsung', 'Nokia','MI']
deviceString = 'Device_ID='
combined__device_list = []
final_combined_list =[]
for x in my_device_list:
combined__device_list.append(deviceString + x)
final_combined_list = ' OR '.join(e for e in combined__device_list)
Can someone please help
Use f-strings in join for custom strings:
my_device_list = ['Iphone', 'Samsung', 'Nokia','MI']
deviceString = 'Device_ID'
out = ' OR '.join(f'{deviceString}="{e}"' for e in my_device_list)
print (out)
Device_ID="Iphone" OR Device_ID="Samsung" OR Device_ID="Nokia" OR Device_ID="MI"
You may use the join method to get your output.
If you want an output like Iphone Samsung Nokia MI:
print(" ".join(my_device_list))
If you want an output like Iphone, Samsung, Nokia, MI:
print(", ".join(my_device_list))
Long story short, use Separator.join(List) to concatenate all items in a list.
Just change your
combined__device_list.append(deviceString + x)
To
combined__device_list.append(deviceString + "\"" + x + "\"")
You will get you want.

x.split has no effect

For some reason x.split(':', 1)[-1] doesn't do anything. Could someone explain and maybe help me?
I'm trying to remove the data before : (including ":") but it keeps that data anyway
Code
data = { 'state': 1, 'endTime': 1518852709307, 'fileSize': 000000 }
data = data.strip('{}')
data = data.split(',')
for x in data:
x.split(':', 1)[-1]
print(x)`
Output
"state":1
"endTime":1518852709307
"fileSize":16777216
It's a dictonary, not a list of strings.
I think this is what you're looking for:
data = str({"state":1,"endTime":1518852709307,"fileSize":000000}) #add a str() here
data = data.strip('{}')
data = data.split(',')
for x in data:
x=x.split(':')[-1] # set x to x.split(...)
print(x)
The script below prints out:
1
1518852709307
0
Here is a one-liner version:
print (list(map(lambda x:x[1],data.items())))
Prints out:
[1, 1518852709307, 0]
Which is a list of integers.
Seems like you just want the values in the dictionary
data = {"state":1,"endTime":1518852709307,"fileSize":000000}
for x in data:
print(data[x])
I'm not sure, but I think it's because the computer treats "state" and 1 as separate objects. Therefore, it is merely stripping the string "state" of its colons, of which there are none.
You could make the entire dictionary into a string by putting:
data = str({ Your Dictionary Here })
then, print what you have left in for "for x in data" statement like so:
for x in data:
b = x.split(':', 1)[-1] # creating a new string
print(b)
data in your code is a dictionary. So you can just access your the values of it like data[state] which evaluates to 1.
If you get this data as a string like:
data = "{'state':1, 'endTime':1518852709307, 'fileSize':000000}"
You could use json.loads to convert it into a dictionary and access the data like explained above.
import json
data = '{"state":1, "endTime":1518852709307, "fileSize":0}'
data = json.loads(data)
for _,v in data.items():
print(v)
If you want to parse the string yourself this should work:
data = '{"state":1,"endTime":1518852709307,"fileSize":000000}'
data = data.strip('{}')
data = data.split(',')
for x in data:
x=x.split(':')[-1]
print(x)

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 parse csv to lists

I have a csv file thru which I want to parse the data to the lists.
So I am using the python csv module to read that
so basically the following:
import csv
fin = csv.reader(open(path,'rb'),delimiter=' ',quotechar='|')
print fin[0]
#gives the following
['"1239","2249.00","1","3","2011-02-20"']
#lets say i do the following
ele = str(fin[0])
ele = ele.strip().split(',')
print ele
#gives me following
['[\'"1239"', '"2249.00"', '"1"', '"3"', '"2011-02-20"\']']
now
ele[0] gives me --> output---> ['"1239"
How do I get rid of that ['
In the end, I want to do is get 1239 and convert it to integer.. ?
Any clues why this is happening
Thanks
Edit:*Never mind.. resolved thanks to the first comment *
Change your delimiter to ',' and you will get a list of those values from the csv reader.
It's because you are converting a list to a string, there is no need to do this. Grab the first element of the list (in this case it is a string) and parse that:
>>> a = ['"1239","2249.00","1","3","2011-02-20"']
>>> a
['"1239","2249.00","1","3","2011-02-20"']
>>> a[0]
'"1239","2249.00","1","3","2011-02-20"'
>>> b = a[0].replace('"', '').split(',')
>>> b[-1]
'2011-02-20'
of course before you do replace and split string methods you should check if the type is string or handle the exception if it isn't.
Also Blahdiblah is correct your delimiter is probably wrong.

Categories