Sufiyan Ghori
Sufiyan Ghori

Reputation: 18753

Clean conversion from int list to character and then back to int list, in Python

I want to convert the list of Integers in Python into Characters,

Here is what I have done,

S = [55, 58, 5, 13, 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91]

D = ""
for i in S:
    D += chr(i)
D = ''.join(map(str, D))

This wouldn't work because the chr value of 13 is \r , it will return the start of the line and will cause the expulsion of first four values.

The output will be the character values for 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91 only (the first four values will be removed due to \r)

Here is the output,

♫♀▬¶FSZET[P[

So, It cannot be converted back to the original Integer value.

The second approach,

If i do this,

S = [55, 58, 5, 13, 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91]
print(repr( ", ".join(map(str, map(chr, S)))))

It works but it will output,

'7, :, \x05, \r, \x0e, \x0c, \x16, \x14, F, S, Z, E, T, [, P, ['

But, If i convert it back to integer using ord then each character will be converted separately including x , \ etc....

D = repr( ", ".join(map(str, map(chr, S))))
for i in D:
    print(ord(i))

I want to convert the integer to the string and then back to the integers. The final output should be the original integer List which was,

[55, 58, 5, 13, 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91]

How could I acheive this. ?

Upvotes: 0

Views: 226

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279305

import ast

string_version = str(S)
list_version = ast.literal_eval(string_version)

Also, the following works fine:

string_version = ''.join(chr(s) for s in S)
list_verison = list(ord(s) for s in string_version)

The \r does not remove the first four characters, it just makes it print that way to a terminal, and the string isn't very human-readable.

You can abbreviate a bit further if you want:

string_version = ''.join(map(chr, S))
list_version = list(map(ord, string_version))

The \r might cause a problem if you need to print the string_version to a terminal, then copy-paste it and read it back, or something like that. In that case you could do:

string_version = repr(''.join(map(chr, S)))
# print, copy, paste, etc.
list_version = list(map(ord, ast.literal_eval(string_version)))

It's a less readable form than my first code snippet, but it might be more compact.

Upvotes: 2

Raghav Malik
Raghav Malik

Reputation: 840

Given a list integers s, you can create the output string d with:

s = [...]
d = "".join(map(chr, [letter for letter in s]))

You can convert the string d back into a list with:

d = "..."
s = map(int, map(ord, list(d)))

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142176

You could use bytearray here:

S = [55, 58, 5, 13, 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91]

as_str = str(bytearray(S))
print list(bytearray(as_str))
# [55, 58, 5, 13, 14, 12, 22, 20, 70, 83, 90, 69, 84, 91, 80, 91]

Upvotes: 1

Related Questions