1

When provided text as input string, and rule as input integer, challenge is to find ASCII value sum then convert back to string based on new numeric value.

My code appears on the right track, but given ascii_encrypt("a",1), for example, my current output is b'b' when it should be 'b'. I'm new to the encode function, which I'm guessing is tripping me up.

def ascii_encrypt(text, rule):
    text = sum([ord(c) for c in text])
    if not text:
        return ""
    else:
        encrypted_text = chr(text + rule)
        return encrypted_text.encode('utf-8')
3
  • Why are you encoding the result in UTF-8? Commented Apr 4, 2017 at 23:42
  • one test case had mixed letters, so i thought this would account for that Commented Apr 4, 2017 at 23:53
  • 1
    I dont understand what is the use of this line : text = sum([ord(c) for c in text]) . Do you want to use this function with strings larger than 1 character ? Commented Apr 5, 2017 at 1:20

1 Answer 1

2

Simply remove, .encode('utf-8'). You don't need to encode it and it's causing your issue. You can't include this part and achieve desired functionality.

def ascii_encrypt(text, rule):
    text = sum([ord(c) for c in text])
    if not text:
        return ""
    else:
        encrypted_text = chr(text + rule)
        return encrypted_text

print(ascii_encrypt("a",1))
Sign up to request clarification or add additional context in comments.

4 Comments

What if I don't want to print but instead just return the value without encoding it?
Exactly, you don't need to print it or encode it. Sending your strings as byte strings isn't a good idea. Just leave the string not encoded. If you could mark as solution, it'd help a lot.
here's what i get with the above code (minus print function): UnicodeEncodeError: 'ascii' codec can't encode character '\u0693' in position 11: ordinal not in range(128)
@Mr.Jibz which line in the above code causes a UnicodeEncodeError? I can't see this happening, even if you are still using Python 2. (And in case you are: it's time to switch now!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.