0

Can anyone explain to me why the following snippet doesn't work? The resulting hex string will be only two characters long.

#!/usr/bin/python

s = 'Hello, World!'

hs = ''
for i in range(len(s)):
    c = s[i:1]
    hs += c.encode('hex')
print hs
0

2 Answers 2

2

Because on each loop, you're trying to slice from i (which is increasing) to position 1 - which means after i > 1, you get empty strings...

It looks though, that you're doing:

from binascii import hexlify

s = 'Hello, World!'
print hexlify(s)

... the hard way...

Sign up to request clarification or add additional context in comments.

1 Comment

And I know it can be done in a simpler way, I just wondered why this one wasn't working, and the reason was that I thought the second figure after the colon in the slice notation was a length, not an index.
2

c = s[i:1] should be c = s[i:i+1] or c[i]

In python you can loop over the string itsellf, so no need of slicing in your example:

hs = ''
for c in s:
    hs += c.encode('hex')

or a one-liner using str.join, which is faster than concatenation:

hs = "".join([c.encode('hex') for c in s])

7 Comments

Yes, of course. I've been doing Perl until now, so I'm rather new at this. Thank you very much.
Yes, I know that, I just used this as a silly example of something that I didn't think was working.
Oh, I love your one-liner, so pretty and elegant :)
@Ashiwini Chaudhary just one complement: join() also works with generator, not just lists, so: this is valid: hs = "".join((c.encode('hex') for c in s))
@Volatility the problem is that .encode('hex') won't work in Python 3.x, which is why I prefer to use hexlify
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.