1

I am trying, in the following code, to encrypt a message. The problem is that my result comes up in a list format instead of a string. How do I make it into a string?

user2097674
  • 31
  • 1
  • 3
  • As far as I can tell, you are trying to do create a string of alternating characters. You want this: `def stringEncrypter(A): return "".join(A[0:-1:2] + A[1:-1:2])` – hughdbrown Mar 12 '13 at 20:34

2 Answers2

2

finalArray is clearly a list:

finalArray = []

To convert it to a string, use join:

print ''.join(finalArray)

But first, you probably do not want these nested lists. You should use extend, not append:

def stringEncrypter(A):
    length = len(A)
    finalArray = []

    if length%2 == 0:
            firstArray=[]*(length/2)
            secondArray=[]*(length/2)
    else:
            firstArray=[]*((length+1)/2)
            secondArray=[]*((length-1)/2)

    for x in range(0, length-1):
            if x%2 == 0:
                    firstArray.append(A[x:x+1])
                    secondArray.append(A[x+1:x+2])
    finalArray.extend(firstArray)
    finalArray.extend(secondArray)

    print ''.join(finalArray)
Pavel Anossov
  • 60,842
  • 14
  • 151
  • 124
2

You need to flatten the nested lists in your result and then turn it into a string. Here's one way to do it:

>>> import itertools
>>> result = [['I', 'R', 'A', ' ', 'O'], [' ', 'E', 'D', 'Y', 'U']]
>>> ''.join(itertools.chain(*result))
'IRA O EDYU'
Tom Offermann
  • 1,391
  • 12
  • 12