Xozu
Xozu

Reputation: 101

For loop output to a string in python

So i wrote a code that takes a string and print out the ascii code but i have this problem that i'm printing out the ascii for every letter in a for loop and in the end i want it to be a string of a number.

This is the code:

getname='test'
for letter in getname:
    print ord(letter)

And the output is:

116
101
115
116

How can i take the for loop output and make it a string? in the end i want it to be like this:

116101115116

Thanks.

Upvotes: 0

Views: 3040

Answers (2)

Chris_Rands
Chris_Rands

Reputation: 41198

You can do a one line statement like this

>>> "".join(str(ord(x)) for x in getname)
'116101115116'

Upvotes: 2

pta2002
pta2002

Reputation: 185

You want to create a string and append to it, like this:

getname = 'test'
result = ''
for letter in getname:
    result += ord(letter)
print result

Output:

116101115116

Upvotes: 1

Related Questions