I wanted to create a function that could hash a string using sha.
Here's my code:
def hashNow(number,string):
for i in range (number):
hashH = int(hashlib.sha1(string.hexdigest(),16)
print hashH #debug purpose
indexing = hashH % len(arrays)
arrays[indexing] = 1
When I compile this code, it prints SyntaxError: invalid syntax pointing at the print hashH. Based on my experience, invalid syntax error usually is an error carrier from the previous line.
My question: am I implementing the hexdigest incorrectly? Why string.hexdigest() cause a syntax error?
One syntax error is that there is missing a closing bracket of the int()-call. Another error is, that sha1() returns an object what can't be converted to int (I'm trying it in python 2.7). By the way, sha-1 isn't really safe, sha-2 and sha-3 are better.
Related
I was taking a look to a couple of related questions which treats about the same issue, but I still don't find a way to solve it.
It turns out that every time I execute a Django-related command, it prints me out the expected output plus something like this:
/Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py:307: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
return name == ":memory:" or "mode=memory" in force_text(name)
And here is the context of that line:
def is_in_memory_db(self, name):
return name == ":memory:" or "mode=memory" in force_text(name)
Despite the Django server works, it's kind of annoying having always this message printed out on my screen. So, why is this happening and how could this be solved?
use decode('utf-8') to make correct comparing:
name.decode('utf-8') == ":memory:" or "mode=memory" in force_text(name)
Use full info:
Unicode HOWTO
Solving Unicode Problems in Python 2.7
I am trying to update my configuration.ini file's, [Financial Times: Financial-Services] section's last_entry_id with the following string: http://www.ft.com/cms/s/0/46858280-36f4-11e6-a780-b48ed7b6126f.html?ftcamp=published_links%2Frss%2Fcompanies_financial-services%2Ffeed%2F%2Fproduct
Here is my configuration.ini file's corresponding section:
[Financial Times: Financial-Services]
feed_updated_on =
feed_updated_field = ['updated']
link = http://www.ft.com/rss/companies/financial-services
last_entry_id =
id_field = link
But in my code, when I try the following line:
id_of_first_link = 'http://www.ft.com/cms/s/0/46858280-36f4-11e6-a780-b48ed7b6126f.html?ftcamp=published_links%2Frss%2Fcompanies_financial-services%2Ffeed%2F%2Fproduct'
feed_link['last_entry_id'] = id_of_first_link
I get the error:
ValueError: invalid interpolation syntax in 'http://www.ft.com/cms/s/0/46858280-36f4-11e6-a780-b48ed7b6126f.html?ftcamp=published_links%2Frss%2Fcompanies_financial-services%2Ffeed%2F%2Fproduct' at position 90
feed_link is the reference name of [Financial Times: Financial-Services] in the configuration.ini file. How to resolve this issue?
The exception refers to an invalid interpolation syntax
This is because in Python you're able to interpolate strings with the following syntax:
mystring = "Hello, my name is %s"
print(mystring % 'StackOverflow')
I think that at some point in configparser, it must be using this syntax, and therefore is getting a string that it cannot handle correctly.
There are a few ways to get around this. You can either use the str.replace() that I showed you, which escapes % by using a double percent sign %%...
Or you can try to provide a raw string instead, with this syntax:
id_of_first_link = r'http://www.ft.com/cms/s/0/46858280-36f4-11e6-a780-b48ed7b6126f.html?ftcamp=published_links%2Frss%2Fcompanies_financial-services%2Ffeed%2F%2Fproduct'
Note the r before the starting single-quote.
Raw strings will also allow you to type strings like r'C:\Windows\system32' without the backslashes escaping characters accidently.
I'm learning python in Coursera, I tried the assignment for the course but am not getting the desired result. This program is supposed to extract '0.8475' and convert it to float before printing it.
text = "X-DSPAM-Confidence: 0.8475";
pos=text.find('0');
s=text[pos:len(text)];
p=0.0;
p=(float)s;
print p;
Everytime I run this code, I get a ParseError: bad input on line 5.
What am I doing wrong?
As #ZdaR mentions, the call to the float function must pass the parameter inside the parentheses as p = float(s). I tested this in Python IDLE and the program worked correctly.
Also note that you should not end lines with ; in Python. The whitespace itself will handle that for you when you start a new line.
I am working on converting an existing program from Python2 to Python3. One of the methods in the program authenticates the user with a remote server. It will prompt the user to enter in a password.
def _handshake(self):
timestamp = int(time.time())
token = (md5hash(md5hash((self.password).encode('utf-8')).hexdigest()
+ str(bytes('timestamp').encode('utf-8'))))
auth_url = "%s/?hs=true&p=1.2&u=%s&t=%d&a=%s&c=%s" % (self.name,
self.username,
timestamp,
token,
self.client_code)
response = urlopen(auth_url).read()
lines = response.split("\n")
if lines[0] != "OK":
raise ScrobbleException("Server returned: %s" % (response,))
self.session_id = lines[1]
self.submit_url = lines[3]
The problem with this method is that after the integer is converted to a string, it needs to be encoded. But as far as I can tell, it is already encoded? I found this question but I was having a hard time applying that to the context of this program.
This is the line giving me problems.
+ str(bytes('timestamp').encode('utf-8'))))
TypeError: string argument without an encoding
I have tried playing around with alternate ways of doing this, all with varying types of errors.
+ str(bytes('timestamp', 'utf-8'))))
TypeError: Unicode-objects must be encoded before hashing
+ str('timestamp', 'utf-8')))
TypeError: decoding str is not supported
I'm still getting started learning Python (but I have beginner to intermediate knowledge of Java), so I am not completely familiar with the language yet. Does anyone have any thoughts on what this issue might be?
Thanks!
This error is due to how you create bytes in python 3.
You will not do bytes("bla bla") but just b"blabla" or you need to specify an encoding type like bytes("bla bla","utf-8") because it needs to know what was the original encoding before turning it into an array of numbers.
Then the error
TypeError: string argument without an encoding
Should disappear.
You have either bytes or str. If you have a bytes value and you want to turn it in str you should do:
my_bytes_value.decode("utf-8")
And it will return you a str.
I hoped it help ! Have a nice day !
I am trying to compute the hash function for a string and I am receiving a syntax error about how to convert a character at position x to an integer value. Anyone know how to correctly do this?
def hashFunction(inputString, r, m):
for x in range(0,len(inputString)-1):
hashValue = (hashValue*r+(ord)inputString[x])% m
return hashValue
I see two issues, first of all, you're not calling ord on an argument. You probably want this:
hashValue = (hashValue*r+ord(inputString[x]))% m
Notice how I wrapped the argument in parentheses instead of around the function name.
The second thing is that you're using the value of hashValue when it hasn't been assigned to yet. This will give you an error when you call the function.