Getting Different O/P on python2.7 & python 3.5 - python

I'm just a beginner in python.
I was just writing some code to print table of any number and I surprisingly got different answers on python v2.7 & python v3.5!
This occur only when I use string function, not when I use comma(,).

The difference is the type of 'n'. It is treated as an integer than you get the numeric operation '', in the other case it is treated as string with the string operation ''. Try out type(n) after you read it and you will see the difference.

Related

How do I make my program acknowledge that a variable contains an integer in Python

I'm new to using Python (and dynamically typed languages in general) and I'm having trouble with the my variables being incorrectly-typed at run time. The program I've written accepts 6 variables (all should be integers) and performs a series of calculations using them. However, the interpreter refuses to perform the first multiplication because it believes the variables are type 'str'. Even when I enter integers for all values it breaks at run-time and claims I've entered strings. Shouldn't Python treat anything that walks and quacks like an int as if it were an int?
Thanks in advance.
PS: I'm running Python 3.4.0, if that helps.
input() always returns a string. If you wanted to have an integer, convert your input.
variable = int(variable)
Python doesn't coerce, you need to convert explicitly. Dynamic typing doesn't mean Python will read your mind. :-)
You can think of it this way: "Duck Typing" applies to the type of a variable, not of the variable's contents. A string variable is something that can for example be indexed with [] or added to other strings with + and even repeated several times with * {some integer}, but you can't add a string to an integer, even if the string happens to be a number.
The number-ness of a string has nothing to do with the type.

how to translate "0x%llx" from C to python

I'm reading some strings from a memory buffer, written by a C program. I need to fetch them using python and print them. however when I encounter a string containing %llx python does not know how to parse this:
"unsupported format character 'l' (0x6c) at index 14"
I could use replace('%llx','%x') but than it would not be a long long.. would python handle this correctly in this case?
than it would not be a long long
Python (essentially) doesn't have any concept of a long long. If you're pulling long longs from C code, just use %x and be done with it -- you're not ever going to get values from the C code that are out of the long long range, the only issue that could arise is if you were trying to send them from Python code into C. Just use (with a new-style format string):
print('{0:x}'.format(your_int))
Tested on both Python v3.3.3 and v2.7.6 :
>>> print('%x' % 523433939134152323423597861958781271347434)
6023bedba8c47434c84785469b1724910ea

How to strip letters out of a string and compare values?

I have just learned Python for this project I am working on and I am having trouble comparing two values - I am using the Python xlwt and xlrd libraries and pulling values of cells from the documents. The problem is some of the values are in the format 'NP_000000000', 'IPI00000000.0', and '000000000' so I need to check which format the value is in and then strip the characters and decimal points off if necessary before comparing them.
I have tried using S1[:3] to get the value without alphabet characters, but I get a 'float is not subscriptable' error
Then I tried doing re.sub(r'[^\d.]+, '', S1) but I get a Typerror: expected a string or buffer
I figured since the value of the cell that is being returned via sheet.cell( x, y).value would be a string since it is alphanumeric, but it seems like it must be returned as a float
What is the best way to format these values and then compare them?
You are trying to get the numbers from the strings in the format shown? Like to get 2344 from NP_2344? If yes then use this
float(str(S1)[3:])
to get what you want. You can change float to int.
It sounds like the API you're using is returning different types depending on the content of the cells. You have two options.
You can convert everything to a string and then do what you're currently doing:
s = str(S1)
...
You can check the types of the input and act appropriately:
if isinstance(S1, basestring):
# this is a string, strip off the prefix
elif isinstance(S1, float):
# this is a float, just use it

How can I get Python to use upper case letters when printing hexadecimal values?

In Python v2.6 I can get hexadecimal for my integers in one of two ways:
print(("0x%x")%value)
print(hex(value))
However, in both cases, the hexadecimal digits are lower case. How can I get these in upper case?
Capital X (Python 2 and 3 using sprintf-style formatting):
print("0x%X" % value)
Or in python 3+ (using .format string syntax):
print("0x{:X}".format(value))
Or in python 3.6+ (using formatted string literals):
print(f"0x{value:X}")
Just use upper().
intNum = 1234
hexNum = hex(intNum).upper()
print('Upper hexadecimal number = ', hexNum)
Output:
Upper hexadecimal number = 0X4D2
print(hex(value).upper().replace('X', 'x'))
Handles negative numbers correctly.
By using uppercase %X:
>>> print("%X" % 255)
FF
Updating for Python 3.6 era: Just use 'X' in the format part, inside f-strings:
print(f"{255:X}")
(f-strings accept any valid Python expression before the : - including direct numeric expressions and variable names).
The more Python 3 idiom using f-strings would be:
value = 1234
print(f'0x{value:X}')
'0x4D2'
Notes (and why this is not a duplicate):
shows how to avoid capitalizing the '0x' prefix, which was an issue in other answers
shows how to get variable interpolation f'{value}'; nobody actually ever puts (hardcoded) hex literals in real code. There are plenty of pitfalls in doing variable interpolation: it's not f'{x:value}' nor f'{0x:value}' nor f'{value:0x}' nor even f'{value:%x}' as I also tried. So many ways to trip up. It still took me 15 minutes of trial-and-error after rereading four tutorials and whatsnew docs to get the syntax. This answer shows how to get f-string variable interpolation right; others don't.

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

Categories

Resources