0

I have some code that turns a list of intergers into the characters they represent in ascii This all works fine but it prints every character in a new line. I fixed this by adding 'end=''' to the print statement. However, I want this output (a one line string) inside a variable so I can do different things with it. How do I do this?

This is the code with the working print statement:

a = [116, 101, 115, 116, 115, 116, 114, 105, 110, 103]

for x in range(len(a)):
    data = (chr(a[x]))
    print(data, end='')

I already tried things like rsplit and join but nothing gives the correct outcome.

Thank you for any help you can give me.

3 Answers 3

3

This is possible with a join and list comprehension:

data = ''.join([chr(a[x]) for x in range(len(a))])

Note that you definitely did not want to iterate over the indices but the elements themselves, so a better approach would come from a foreach loop:

data = ''.join([chr(x) for x in a])

A functional approach seems not bad too:

data = ''.join(map(chr, a))

Post that you simply have to:

print(data)
Sign up to request clarification or add additional context in comments.

3 Comments

Or even join with a generator expression - data = ''.join(chr(x) for x in a).
@wwii, that is not as efficient as list comp.
.. 5% slower for 100 million ... If time efficiency is the goal you should point out that map is the fastest.
0

Try this :

import sys

a = [116, 101, 115, 116, 115, 116, 114, 105, 110, 103]

for x in range(len(a)):
    data = (chr(a[x]))
    sys.stdout.write(data)

Output :

teststring

Comments

0
a = [116, 101, 115, 116, 115, 116, 114, 105, 110, 103]

# empty string
result = ""
# loops trough the list
for x in a:
    # the converted character is added to the string
    result + = chr(x)

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to ADD EXPLANATION and give an indication of what limitations and assumptions apply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.