symbols being printed when english alphabet wanted - python-3.4

I am writing this code and have recently come across an error. I have no idea why this is happening. In theory, the english alphabet should be being printed. However, instead of the english alphabet, symbols are being printed instead.
I can not paste the symbols for some reason, but if you ran the code yourself, you'll understand what I mean.
My full code is posted below.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")
if choice == "e":
message = input("Please insert the message you would like to use: ")
keyword = input("Please insert the keyword you would like to use: ")
ik = len(keyword)
i = 0
string = ''
for A in message:
message1 = (ord(A)) - 96
key1 = (ord(keyword[i])) - 96
addition = message1 + key1
string += (chr(addition))
if i >= ik:
i = 0
else:
i += 1
print (string)

You need to add back the 96 you originally took away :) Alternatively, use the Caesar cipher formula as adding back 96 will still result in symbols appearing (I did the ocr coursework already)
addition = message1 + key1 + 96
your code will not work if the keyword is shorter than the message, so use the modulo operator (%) on i with the length of the keyword inside the line:
key1 = (ord(keyword[i])) - 96

Related

Having Trouble converting a string to bytes

I'm trying to convert a string to a byte, thats what I've done.
I want to send out a Modbusprotocol via serial and put it together in bitstring:
tiger = '01'
read = '03'
ac_val = '0031'
word = '0002'
code = tiger+read+ac_val+word
print(code)
010300310002
#now i want to put thist string in a bitstring with the function:
codeh = bytes.fromhex(code)
codeh = b'\x01\x03\x001\x00\x02 #This is what i got
But i was expecting:
codeh = b'\x01\x03\x00\x31\x00\x02
I have no idea why the output is like this.
What it's showing in the output is the ASCII representation of the byte values. Hex 31 corresponds to the ascii character '1'. Try this to see a demonstration:
bytes.fromhex('415343494921')
Here's a chart that shows these low values: https://en.wikipedia.org/wiki/ASCII#Control_code_chart

The encryption won't decrypt

I was given an encrypted copy of the study guide here, but how do you decrypt and read it???
In a file called pa11.py write a method called decode(inputfile,outputfile). Decode should take two parameters - both of which are strings. The first should be the name of an encoded file (either helloworld.txt or superdupertopsecretstudyguide.txt or yet another file that I might use to test your code). The second should be the name of a file that you will use as an output file.
Your method should read in the contents of the inputfile and, using the scheme described in the hints.txt file above, decode the hidden message, writing to the outputfile as it goes (or all at once when it is done depending on what you decide to use).
The penny math lecture is here.
"""
Program: pennyMath.py
Author: CS 1510
Description: Calculates the penny math value of a string.
"""
# Get the input string
original = input("Enter a string to get its cost in penny math: ")
cost = 0
Go through each character in the input string
for char in original:
value = ord(char) #ord() gives us the encoded number!
if char>="a" and char<="z":
cost = cost+(value-96) #offset the value of ord by 96
elif char>="A" and char<="Z":
cost = cost+(value-64) #offset the value of ord by 64
print("The cost of",original,"is",cost)
Another hint: Don't forget about while loops...
Another hint: After letters -
skip ahead by their pennymath value positions + 2
After numbers - skip ahead by their number + 7 positions
After anything else - just skip ahead by 1 position
The issue I'm having in that I cant seem to get the coding right to decode the file it comes out looking the same. This is the current code I have been using. But once I try to decrypt the message it stays the same.
def pennycost(c):
if c >="a" and c <="z":
return ord(c)-96
elif c>="A" and c<="Z":
return ord(c)-64
def decryption(inputfile,outputfile):
with open(inputfile) as f:
fo = open(outputfile,"w")
count = 0
while True:
c = f.read(1)
if not c:
break;
if count > 0:
count = count -1;
continue
elif c.isalpha():
count = pennycost(c)
fo.write(c)
elif c.isdigit():
count = int(c)
fo.write(c)
else:
count = 6
fo.write(c)
fo.close()
inputfile = input("Please enter the input file name: ")
outputfile = input("Plese enter the output file name(EXISTING FILE WILL BE OVER WRITTEN!): ")
decryption(inputfile,outputfile)

IndexError: list index out of range, scores.append( (fields[0], fields[1]))

I'm trying to read a file and put contents in a list. I have done this mnay times before and it has worked but this time it throws back the error "list index out of range".
the code is:
with open("File.txt") as f:
scores = []
for line in f:
fields = line.split()
scores.append( (fields[0], fields[1]))
print(scores)
The text file is in the format;
Alpha:[0, 1]
Bravo:[0, 0]
Charlie:[60, 8, 901]
Foxtrot:[0]
I cant see why it is giving me this problem. Is it because I have more than one value for each item? Or is it the fact that I have a colon in my text file?
How can I get around this problem?
Thanks
If I understand you well this code will print you desired result:
import re
with open("File.txt") as f:
# Let's make dictionary for scores {name:scores}.
scores = {}
# Define regular expressin to parse team name and team scores from line.
patternScore = '\[([^\]]+)\]'
patternName = '(.*):'
for line in f:
# Find value for team name and its scores.
fields = re.search(patternScore, line).groups()[0].split(', ')
name = re.search(patternName, line).groups()[0]
# Update dictionary with new value.
scores[name] = fields
# Print output first goes first element of keyValue in dict then goes keyName
for key in scores:
print (scores[key][0] + ':' + key)
You will recieve following output:
60:Charlie
0:Alpha
0:Bravo
0:Foxtrot

decoding an ASCII character message

I have no idea what im doing I need to decode mmZ\dxZmx]Zpgy, I have an example but not sure what to do please help!
If (EncryptedChar - Key < 32) then
DecryptedChar = ((EncryptedChar - Key) + 127) - 32
Else
DecryptedChar = (EncryptedChar - Key)
the key us unknown 1-100
Use ord and chr to convert between the ordinals (ord) of the ASCII value and the and the characters (chr) they represent.
Then you can loop through your string and apply the your algorithm to each.
For example:
import sys
SecretMessage = "mmZ\dxZmx]Zpgy"
Key = 88
for Letter in SecretMessage:
EncryptedChar = ord(Letter)
if (EncryptedChar - Key) < 32:
DecryptedChar = ((EncryptedChar - Key) + 127) - 32
else:
DecryptedChar = (EncryptedChar - Key)
sys.stdout.write(chr(DecryptedChar))
Run this to see the output. I'll leave the exercise of finding the key value 88 up to you (hint: it involves iterations). You also appear to be missing the first letter from SecretMessage (probably a :).

check if a string's first 16 char is a number

I'm storing some files in database which has filename like 1839341255115211butterflies.jpg.I need to show this filename to the user as butterflies.jpg.I need to remove the first 16 digit and then show the filename.Added to it I also have few filenames which don't have this 16digit addition prior to the filename.Now my question is how do I identify if this string has 16digit numeric value prior to the filename, based on it remove the 1st 16digit and display just the filename. I'm aware of how to remove the first 16digit and retrive the filename but need help on how to identify a string that has 16digit.
Any suggestion is much appreciated.
A regular expression looks like a good fit here:
^[0-9]{16}
The above will match on strings that start with 16 digits (0 to 9).
Usage:
if(Regex.Match(fileName, #"^[0-9]{16}").Success)
{
fileName = fileName.Remove(0, 16);
}
string.Remove will work quite nicely:
var str = "1839341255115211butterflies.jpg";
str = str.Remove(0, 16);
Console.WriteLine(str);
With Linq:
remove all digits at the beginning until 16 digits:
string file = "1839341255115211butterflies.jpg";
string extension = Path.GetExtension(file);
string fileName = Path.GetFileNameWithoutExtension(file);
fileName = new string(fileName.Where((c, i) => i >= 17 || !Char.IsDigit(c)).ToArray());
file = fileName + extension;
Demo
Edit: If you just want to know if the first 16 chars are digits, it's easier and more readable:
bool startsWith16Digits = file.Take(16).All(Char.IsDigit);

Resources