matsp888
matsp888

Reputation: 31

String concatenation of hex strings in Python

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

Upvotes: 0

Views: 3060

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

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])

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142226

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

Upvotes: 2

Related Questions