0

In Python, how can I represent an integer value (<256) as a string? For example:

i = 10

How can I create a string "s" that is one-byte long, and the byte has the value 10?

to clarify, I do not want a string "10". I want a string that its 1st (and only) byte has the value of 10.

by the way, I cannot create the string statically:

s = '\x0A' 

because the value is not pre-defined. It is a dynamic number value.

1
  • '\xA' is a syntax error, presumably you meant '\x0A'. Commented Nov 24, 2014 at 19:22

4 Answers 4

1

You can use chr() function as:

>>> chr(60)
'<'
>>> chr(97)
'a'
>>> chr(67)
'C'

To convert back use ord() funtion as:

>>> ord('C')
67
Sign up to request clarification or add additional context in comments.

Comments

1

In Python 2.x, you want:

s = chr(10)

In Python 3.x, strings are Unicode, so you want:

s = bytes([10])

2 Comments

Yeah but it's Unicode, so probably not what you really want.
Why not? The OP has specified that if they'd hardcode the string they'd use '\x0A', not b'\x0A'. It is not clear what version they are using, in any case.
1

why don't you just use chr?

chr(10)
Out[41]: '\n'

chr(255)
Out[42]: '\xff'

Comments

0

Found another answer using struct module working for Python 2:

import struct struct.pack('B', i)

Comments

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.