Defining unpacking format with python's struct - python

I'm trying to unpack a binary file with python's struct.unpack.
when i write struct.unpack("200i",data) it works.
but when i want to use a number of integers found in a previous operation like this: struct.unpack("a[1]i",data) it doesn't work.
p.s: a[1]=200

You have to convert it to string for the function to work:
struct.unpack(str(a[1]) + "i",data)

Related

How does one convert a string list element such as ["+5*-5"] into [+5*-5] in Python 3

How does one convert a string list such as:
string = ["+5*-5"]
into something such as
string = [+5*-5]
so I can evaluate each of this type of expression mathematically without using libraries, import, eval or similar
I've tried the usual type converts and this does not work unfortunately.
Many thanks
A fast and safe way is to use numexpr as follows:
import numexpr
string = ["+5*-5"]
for s in string: # Loop over all elements in your list
print(numexpr.evaluate(string)) # Evaluate and print result

How to convert variable into integer in python? like in php (int)

I have a variable with value like a ="\x01" from my database, how can I convert it into an integer. I have searched the internet but had no success in finding anything.
Anyone have an idea?
In PHP, there is a build-in module to convert it. Is there any similar module for that function in Python?
Simple answer is to use ord().
>>> a = '\x01'
>>> ord(a)
1
But if performance is what you are looking for then refer #chepner's answer.
You can use the struct module for fixed-length values.
>>> a = '\x01'
>>> import struct
>>> struct.unpack("B", a)
(1,)
unpack always returns a tuple, since you can extract multiple values from a single string.

Type inference of values contained in strings stored in a list

I am trying to figure out how to do some nice type inference on the columns of a CSV file.
Are there any libraries that might tell me, for example, that a column contains only integers?
All values are of course available in string format.
I will write my own tool if nothing of this sort already exists, but it seems weird to me that such a basic task does not have a library counterpart somewhere.
Why don't you do the straightforward approach?
if all values can be parsed as integers, to column is integers
otherwise, if all values can be parsed as doubles, to column is doubles
otherwise, the column is all strings
The reason why there is no library for this is probably because it's trivial to implement using the existing string to int and string to double conversion functions.
Regular expressions are good for that, in Python, you could use something like this:
import re
def str_is_num(s):
number_pattern = re.compile("-?^\d+(\.\d+)?$")
return re.match(number_pattern, s) != None
To check whether a cell is a number, you can evaluate str_is_num(cell)

Why use str(id)?

My SDK comes with code appearing with rows like this
id=str(profile["id"])
It makes me wonder why something like the following shouldn't work
id=profile["id"]
Casting I believe is expensive so either the same type can be used or polymorphism at the method called. Can you tell why I must cast the id to a string?
Thank you
There is no casting in Python. Str(67) does not cast. It calls the __str__ method on the integer object, which generates a string representation of itself.
This is necessary to make sure that profile['id'] is a string.
It turns profile[id] into a string, python doesn't do this automatically, and further along in the code, the program probably checks profile[id] against a string. Without this conversion, you would get a typeerror: Trying to compare a string with an integer.
Python does not do arbitrary run time type conversion. You can't use an integer as a string.
It turns profile[id] into a string

Python - Writing to a text file using functions?

i wrote a simple function to write into a text file. like this,
def write_func(var):
var = str(var)
myfile.write(var)
a= 5
b= 5
c= a + b
write_func(c)
this will write the output to a desired file.
now, i want the output in another format. say,
write_func("Output is :"+c)
so that the output will have a meaningful name in the file. how do i do it?
and why is that i cant write an integer to a file? i do, int = str(int) before writing to a file?
You can't add/concatenate a string and integer directly.
If you do anything more complicated than "string :"+str(number), I would strongly recommend using string formatting:
write_func('Output is: %i' % (c))
Python is a strongly typed language. This means, among other things, that you cannot concatenate a string and an integer. Therefore you'll have to convert the integer to string before concatenating. This can be done using a format string (as Nick T suggested) or passing the integer to the built in str function (as NullUserException suggested).
Simple, you do:
write_func('Output is' + str(c))
You have to convert c to a string before you can concatenate it with another string. Then you can also take off the:
var = str(var)
From your function.
why is that i cant write an integer to
a file? i do, int = str(int) before
writing to a file?
You can write binary data to a file, but byte representations of numbers aren't really human readable. -2 for example is 0xfffffffe in a 2's complement 32-bit integer. It's even worse when the number is a float: 2.1 is 0x40066666.
If you plan on having a human-readable file, you need to human-readable characters on them. In an ASCII file '0.5' isn't a number (at least not as a computer understands numbers), but instead the characters '0', '.' and '5'. And that's why you need convert your numbers to strings.
From http://docs.python.org/library/stdtypes.html#file.write
file.write(str)
Write a string to the file. There is no return value. Due to buffering,
the string may not actually show up in
the file until the flush() or close()
method is called.
Note how documentation specifies that write's argument must be a string.
So you should create a string yourself before passing it to file.write().

Categories

Resources