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
matsp888
  • 31
  • 1
  • 6

2 Answers2

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...

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • 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. – matsp888 May 25 '13 at 12:19
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])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Yes, of course. I've been doing Perl until now, so I'm rather new at this. Thank you very much. – matsp888 May 25 '13 at 12:12
  • Yes, I know that, I just used this as a silly example of something that I didn't think was working. – matsp888 May 25 '13 at 12:15
  • Oh, I love your one-liner, so pretty and elegant :) – Peter Varo May 25 '13 at 12:16
  • @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))` – Peter Varo May 25 '13 at 12:18
  • @Volatility the problem is that `.encode('hex')` won't work in Python 3.x, which is why I prefer to use `hexlify` – Jon Clements May 25 '13 at 12:18
  • @PeterVaro I know that, but in case of `str.join` we should always use a list comprehension. http://stackoverflow.com/questions/9060653/list-comprehension-without-python/9061024#9061024 – Ashwini Chaudhary May 25 '13 at 12:25
  • @AshwiniChaudhary There is indeed no performance or memory reason to use a generator expression, but the difference is minuscule and using a generator expression saves a pair of brackets and reads more naturally, which is enough of a reason for me. –  May 25 '13 at 12:38