Home > Software design >  How to Separate Letters Inside a List?
How to Separate Letters Inside a List?

Time:11-25

I have this piece of code

First = "152 162 152 145 162 167 150 172 153 162 145 170 141 16"
First = list(First.split())
solve = " "
for i in First:
    solve  = chr(int(i, base=8))
print(solve)

what I stuck in, is how to separate letters inside a list instead of print all letter together. I tried solve = (solve.split(",") for sep in solve) but it's give me an error. what I will do exactly is to take an ord() value of each letter and subtract 4 then return it to str by chr()

CodePudding user response:

You can use a list comprehension:

data = "152 162 152 145 162 167 150 172 153 162 145 170 141 16"
output = [chr(int(x, base=8)) for x in data.split()]
print(output) # ['j', 'r', 'j', 'e', 'r', 'w', 'h', 'z', 'k', 'r', 'e', 'x', 'a', '\x0e']

If you just want to use your original code, then simply list(solve) will make the list of characters. But note that there is a (perhaps unintended) blank at the beginning of your solve; this happens because you initiated solve with " ", not "".


If you want to subtract 4 from each integer representation of the characters (as you explained in the question), to get the string, then

data = "152 162 152 145 162 167 150 172 153 162 145 170 141 16"
output = ''.join(chr(int(x, base=8) - 4) for x in data.split())
print(output) # fnfansdvgnat]

would provide you with a shortcut.

CodePudding user response:

You can use list directly instead of string as follows:

First = "152 162 152 145 162 167 150 172 153 162 145 170 141 16"
First = list(First.split())
solve = []
for i in First:
    solve.append( chr(int(i, base=8)))
print(solve)

Output: ['j', 'r', 'j', 'e', 'r', 'w', 'h', 'z', 'k', 'r', 'e', 'x', 'a', '\x0e']

You can convert solve to a string as below:

''.join(solve)
  • Related