-1

I am currently making a cipher program in python but I can't seem to solve this one problem:

word = ['a', 'b', 'c']
-----enciphering process-------
message = ['d', 'e', 'f']

print message[x],

What I want to happen:

'def'

What actually happens:

'd e f'

I know why the spaces are there, but I can't seem to get rid of them, I've tried using strip, replace, re.sub, message(map whatever I don't remember), and "".join. Those all work with a pre-determined list but not when I don't know what the list is going to be.

Help please.

*EDIT

What I meant was something like this:

Word = raw_input("Enter a word  ")
Message = list(word)

w = raw_input("Enter a number  ")
w = int(w)
n = len(message)

Letters = ['a', 'b', 'c', 'd' and so on until z]

For y in range(0,n):

   For index in range(0,26):

      X = index + w

      If x > 25:
         x = x - 26

      If message[y] == letters[index]:
         print letters[x],

Not sure how to get rid of the spaces because I don't know what the message is gonna be

3 Answers3

5

print message[x], prints the character message[x], then a space (technically, a "virtual" space that gets turned into a space by the next print statement). If you call it in a loop, you will get d e f.

Instead, print ''.join(message).

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • 3
    `sys.stdout.write()` is another option. It probably won't make a difference here, but if `len(message)` were enormous, this approach may speed up processing time. – jedwards Mar 31 '13 at 07:40
1

Hard to tell what is not working for you. Here's how it looks in interactive python:

>>> message = ['d', 'e', 'f']
>>> print message
['d', 'e', 'f']
>>> print "".join(message)
def
>>> import sys
>>> sys.stdout.writelines(message)
def>>> 

Lines beginning with >>> are statements, other lines are output. The last line is def with no newline, followed by the >>> input prompt.

Old Pro
  • 24,624
  • 7
  • 58
  • 106
0

quick answer is

import sys
# ...
sys.stdout.write(letters[x]) 

but you have a problem in how you structure your code

you want to encode a message you should apply your encoding function to that message for example

word="Hello"
encoded=''.join(map(lambda i: chr(ord(i) ^ 13), word))
print encoded
Muayyad Alsadi
  • 1,506
  • 15
  • 23
  • I would try all of your suggestions, but I have no idea what map does, lambda, or sys.stdout does. But thank you all for the help. – user2228761 Mar 31 '13 at 18:19
  • sys.stdout is the system standard output (it's a file object you can write directly to it). lambda is in short an anonymous function (defined inline in one line that only returns a value) maps loops over elements and pass them to the passed function (the lambda in our case) – Muayyad Alsadi Apr 02 '13 at 06:52