1

I have this code:

str = "text"
x = str.encode('ascii')
print(x)

I got this: b'text'

I want to get this: "116 101 120 116" as string. I want the solution like here I got.

2
  • print(list(x)) gives you the integers. print(*x) would give you space-separated integers. Commented Oct 28, 2018 at 15:26
  • 2
    Please don't redefine builtins like "str" and others. It may break more complex code. Example : isinstance('anything', str) will not work as expected. Commented Oct 28, 2018 at 15:26

2 Answers 2

5
print ([ord(c) for c in 'text'])
# [116, 101, 120, 116]

From docs:

Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.

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

Comments

1

Use map to map each character to its ascii value

str1 = "text"
list(map(ord,str1))

If you need as a string output

str1 = "text"
' '.join(list(map(str,map(ord,str1))))

1 Comment

Seems this is faster than the below method by almost a multiple of 2.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.