We can get a hash value (integer value) of a string using the hash
method. The hash values of two strings that are the same will also be the same.
str.hash
str
: This is the string that calls the hash
method. It is the string whose hash value we want.
The value returned is an integer that is the hash value of the string.
# create some stringsstr1 = "Edpresso"str2 = "is"str3 = "great"# get the hash valuesa = str1.hashb = str2.hashc = str3.hash# print resultputs aputs bputs c
In lines 2-4, we create a few string variables and initialize them with some values.
In lines 7-9, we call the hash
method on the strings created.
In lines 12-14, we print the results.
As we can see when the code is run, we get the hash value of a string when the hash
method is called on it.