简体   繁体   中英

How to print my Caesar cipher without spaces?

I'm trying to print them message from this program without spaces but it always gives me spaces between each letter.

import string
character = []
message = raw_input('What is your message? ').lower()
shift = raw_input('What is your shift key? ')
type = raw_input('Would you like to cipher(c) or decipher(d)? ')
for character in message:
    if str(type) == 'd':
        number = ord(character) - int(shift)
        if number <= 96:
            number = ord(character) + 26 - int(shift)
    if str(type) == 'c':
        number = ord(character) + int(shift)
        if number >= 122:
            number = ord(character) - 26 + int(shift)
    character = chr(number)
    print(character),

Does anyone know hot to print in a sentence so that I can copy the message and recipher it?

add

from __future__ import print_function

to the top of your program and then change

print(character),

to

print(character, end='')

this is explained here .

without the first line you are actually printing (character) which is an expression whose result is character , so it's basically print character, . with the import, print ... changes to print(...) and takes extra arguments that give you more control.

note, this won't work on very old python versions. you probably need 2.6 or later.

[hi scott!]

Lose the comma at the end of the print statement. Of course, then every character will be on a separate line.

Probably best to build up the characters into a string which can be printed all at once.

You can use sys.stdout.write(character) to print individual characters without spaces or newlines much like C's putchar .

For example:

import string
import sys

character = []
message = raw_input('What is your message? ').lower()
shift = raw_input('What is your shift key? ')
type = raw_input('Would you like to cipher(c) or decipher(d)? ')
for character in message:
    if str(type) == 'd':
        number = ord(character) - int(shift)
        if number <= 96:
            number = ord(character) + 26 - int(shift)
    if str(type) == 'c':
        number = ord(character) + int(shift)
        if number >= 122:
            number = ord(character) - 26 + int(shift)
    character = chr(number)
    sys.stdout.write(character),

print ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM