简体   繁体   中英

How to keep spaces in caesar cipher program

I am programming a Caeser Cipher encoder/decoder for my computer science class in Python 3 and I'm struggling to find out how to exclude spaces when each character is shifted.

message = input("type in a message")
messageInt = float(input("type in an integer"))
newStrs = []

for letter in message:
    x = ord(letter)
    x = int(x + messageInt)
    newStrs.append(chr(x))

print("".join(newStrs))

This happends when I try to use an example sentance with spaces, I've tried looking online for answers but I wasn't able to find anything that seemed to work in Python 3 or would output what my teacher expects.

type in a message hello there
type in an integer 3
#khoor#wkhuh

Process finished with exit code 0

Use a simple list comprehension with a ternary to check for the spaces:

message = input("type in a message")
messageInt = int(input("type in an integer"))

print("".join([c if c == ' ' else chr((ord(c)-ord('a')+messageInt)%26+ord('a')) for c in message]))

You can easily generalize to a whitelist of characters using a set :

keep = set(' .,?!')
print("".join([c if c in keep else chr((ord(c)-ord('a')+messageInt)%26+ord('a')) for c in message]))

Output:

khoor wkhuh

To exclude spaces when shifting the characters in your message, you can simply add an if statement to your loop that checks if the current letter is a space. If it is, you can skip the shifting step and just append the space to the newStrs list.

I modified your code as an example (code updated):

# Get the message and shift amount from the user
message = input("type in a message: ")
shift = int(input("type in an integer: "))

# Create a list to store the shifted characters
new_str = []

# Iterate through each character in the message
for letter in message:
    # Check if the character is a space
    if letter == " ":
        # If it is, append a space to the new string and skip the rest of the loop
        new_str.append(" ")
        continue

    # Shift the character by the specified amount
    # First, get the ASCII value of the character
    x = ord(letter)
    # Shift the character and wrap around the alphabet if necessary
    x = (x + shift - 97) % 26 + 97
    # Convert the shifted ASCII value back to a character and append it to the new string
    new_str.append(chr(x))

# Join the shifted characters into a single string and print it
print("".join(new_str))

If you are wondering whats going on with

x = (x + shift - 97) % 26 + 97

This will shift all characters except spaces, so the output will preserve the spaces in the original message.

x = (x + shift - 97) % 26 + 97

This line of code is used to shift the ASCII value of a character by a specified amount and wrap around the alphabet if necessary.

First, the value of x is added to the value of shift:

x + shift

Then, 97 is subtracted from the result:

x + shift - 97

The result is then passed to the % operator, which returns the remainder of the division of the left operand by the right operand. In this case, the remainder of the division of x + shift - 97 by 26 is calculated:

(x + shift - 97) % 26

Finally, 97 is added back to the result:

(x + shift - 97) % 26 + 97

This has the effect of shifting the character by the specified amount, wrapping around the alphabet if necessary, and ensuring that the resulting ASCII value is in the range 97 to 122 (inclusive).

For example, if the value of x is 120 (the ASCII value of 'x'), the value of shift is 3, and the line of code is executed, the following steps will be taken:

120 + 3 = 123 123 - 97 = 26 26 % 26 = 0 0 + 97 = 97

The final result, 97, is the ASCII value of 'a', so the resulting character will be 'a'.

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