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
Related
I am taking a byte as input
b'\xe2I4\xdd\r\xe5\xfcy^4\xd5'
but it gets converted into string.
so when i am to trying to convert this string to byte it is again manipulating it and giving me output as:
b"b'\\xe2I4\\xdd\\r\\xe5\\xfcy^4\\xd5'"
My desired output is that when i provide b'\xe2I4\xdd\r\xe5\xfcy^4\xd5' it convert it into byte as it is without manipulating it or adding any character or symbol.
Any resource or reference will be helpful.
Thanks In Advance
The BAD idea
You could pass the value of input() to eval() function. The function eval() directly evaluates a string as if it were directly executed in Python. Although it might feel like a best feature at first but due to the same reason it is pretty much unsafe to use it within any production-level application, since, the user can execute any code using that which might cause a lot of problems.
Better alternative
You can use a safer alternative to eval() which is ast.literal_eval(). This function evaluates a given string as Python literals (like string, numbers, bytes object, etc.). In case if a string does not contain any literal (like function calls, object creation, assignment, etc.), this function throws an error. Enough about that let's see how you could get this working.
import ast
user_input = input()
eval_expr = ast.literal_eval(user_input)
If you want to check if the input is a bytes literal, you could use the isinstance function to check and then perform required action.
# Optional: Handle if `eval_expr` is not a `bytes` literal
if not isinstance(eval_expr, bytes):
...
So, all you need to do is import the module ast first. Then take the user's input. Thereafter pass this input string to ast.literal_eval() function to evaluate the string.
I wanted to write a Python script to bruteforce hashes that permits the user to insert the hashing algorithm as a string (Result: algorithm = "md5"), but when I tried to use it like this in the hashlib library: guess_hash = hashlib.algorithm(bytes(guess)).hexdigest(), it obviously gave me this error: AttributeError: module 'hashlib' has no attribute 'algorithm'
So I did a quick research and I tried using getattr like this: getattr(hashlib,guess(bytes(guess1))).hexdigest() (probably really wrong) and it gave me this error: TypeError: string argument without an encoding.
What should I do? Thanks in advance and sorry for the noobiness :)
You missed passing the actual algorithm name to the getattr call.
Try this:
getattr(hashlib, 'md5')(bytes(guess)).hexdigest()
That's actually bytes complaining (which it will with Python 3 but not Python 2). It would appear that you've also swapped the meanings of algorithm and guess in your getattr, and you'll want to do something like
getattr(hashlib, algorithm)(bytes(guess, 'utf-8')).hexdigest()
Simple is better than complex. You can just have a bunch of if statements and do the correct call in those. If there are too many, you could use a hashmap where the key is a string and the value a function.
getattr is, however, the correct call to fetch an attribute with a variable, but the error tells you that you cannot convert a string to a bytestring without specifying the encoding. The bytes function allows you to specify encoding like this:
a_byte_string = bytes(a_regular_string, encoding='utf8')
I am trying to check in a number of type float if there is a specific digit.
If it was a string I would use the method find(), and I thought about converting the number first to a string, then use find() and then reconvert it.
But it isn't productive. Is there a special method or faster way of doing it?
Thank you for the help
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.
I need to enter a complex string for handling (UTC time code) and breaking down as part of an assignment. I have started the function like this as required:
def convertWmiDateTime(wmiDateTime):
But when I enter this:
convertWmiDateTime(20061122185433.000000+600)
The variable wmiDateTime stores 2.0061122186e+13
If I use raw_input the value 20061122185433.000000+600 will be stored correctly in wmiDateTime, but not when its called as intended above.
Is there a way to preserve what was typed into the input? A way to stop Pythong calculating and simplifying the number? vb. net would be something like (wmiDateTime As String) is there anything like that for Python?
Thanks for looking.
Your function requires a string as its input parameter. You can't call it with a number (as you're doing).
raw_input() returns a string, so the equivalent would be to call
convertWmiDateTime("20061122185433.000000+600")
Your version treats the time code as a floating point number which a) doesn't have the required precision to preserve all the digits and b) will get the timezone info (+600) added, which leads to wrong results as well.