[Solved] shift each letter of words by value


You need to do the assignment yourself (or there is no point in learning to program) and if you don’t understand the question, you should ask your teacher for clarification.

That said, shifting is quite simple in principle. You can do it by hand. If you have a letter, say A, shifting it by 1 (key = 1) would transform it into B. In the assignment you shift by 2 places, so A would become C, B (in the original word) would be become D and so on. You have to be a bit careful about the end of the alphabet. When shifting by 1, Z becomes A. When shifting by 2, Y becomes A and Z becomes B.

So in your example, HELLO becomes JGNNQ because when shifting 2 places:

H => J

E => G

L => N

O => Q

(Note: I’m using uppercase for readability but your assignment seems to be about working on lowercase characters. I’m assuming you’re only asked to handle lowercase.)

How do you do this? Check out the links you were given. Basically ord() transforms a character into an integer and chr() transforms one such integer into a character. It’s based on the way characters are represented as numbers in the computer. So for a given character, if you transform it into its ord(), you can add the key to shift it and then transform it back into a character with chr().

For wrapping from Y and Z to A and B, you can use the modulus operator (%) for this but be careful, it’s a bit fiddly (you need to calculate the difference between the ord of your character and the ord of ‘a’, apply % 26 (which gives you a number between 0 and 25), then add it to ord(‘a) to have the correct ord). If it’s too complicated, just do it with a couple of IFs.

I’d advise to start with a small program that takes input from the user and prints the output to check that it’s working correctly. You won’t need the input and print in the final version but it will help you to test that your shifting code works correctly.

Then you have the part about reading from a file and writing to a file. Your assignment doesn’t ask the user for input, instead it reads from a file. Your line with open ("word-text.txt","r") as f: looks fine, this should give you the file handle you need to read the data. You can read the data with f.read() and assign it to a variable. I’m not sure what you’ve been taught, but I’d split the string into words with <string>.split() which creates a list of strings (your words).

Then for each word, you use the code you wrote previously to shift the string and you can just write both the original word and the shifted word into the output file. The simplest would probably be to start by opening the output file (in writing mode) and do both the shifting and the writing in one go by looping on the list.

4

solved shift each letter of words by value