Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the first few characters of a string in Python?

Hi I just started learning Python but I'm sort of stuck right now.

I have hash.txt file containing thousands of malware hashes in MD5, Sha1 and Sha5 respectively separated by delimiters in each line. Below are 2 examples lines I extracted from the .txt file.

416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f 56a99a4205a4d6cab2dcae414a5670fd|612aeeeaa8aa432a7b96202847169ecae56b07ee|d17de7ca4c8f24ff49314f0f342dbe9243b10e9f3558c6193e2fd6bccb1be6d2

My intention is to display the first 32 characters (MD5 hash) so the output will look something like this:

416d76b8811b0ddae2fdad8f4721ddbe 56a99a4205a4d6cab2dcae414a5670fd

Any ideas?

like image 666
Rising Lee Avatar asked Jul 30 '12 02:07

Rising Lee


People also ask

How do you extract the first few characters from a string in Python?

To access the first n characters of a string in Python, we can use the subscript syntax [ ] by passing 0:n as an arguments to it. 0 is the starting position of an index. n is the number of characters we need to extract from the starting position (n is excluded).

How do you find the first few letters of a string?

To get the first N characters of a string, we can also call the substring() method on the string, passing 0 and N as the first and second arguments respectively. For example, str. substring(0, 3) returns a new string containing the first 3 characters of str .

How do I find the first 10 characters of a string?

To get the first 10 characters, use the substring() method. string res = str. Substring(0, 10);


2 Answers

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string' 

To get the first 4 letters:

first_four_letters = a_string[:4] >>> 'This' 

Or the last 5:

last_five_letters = a_string[-5:] >>> 'string' 

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f ' first_32_chars = the_string[:32] >>> 416d76b8811b0ddae2fdad8f4721ddbe 
like image 78
TankorSmash Avatar answered Sep 26 '22 06:09

TankorSmash


Since there is a delimiter, you should use that instead of worrying about how long the md5 is.

>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f" >>> md5sum, delim, rest = s.partition('|') >>> md5sum '416d76b8811b0ddae2fdad8f4721ddbe' 

Alternatively

>>> md5sum, sha1sum, sha5sum = s.split('|') >>> md5sum '416d76b8811b0ddae2fdad8f4721ddbe' >>> sha1sum 'd4f656ee006e248f2f3a8a93a8aec5868788b927' >>> sha5sum '12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f' 
like image 24
John La Rooy Avatar answered Sep 22 '22 06:09

John La Rooy