Home > Back-end >  Converting characters to ciphered ASCII values
Converting characters to ciphered ASCII values

Time:04-05

I want to take a word from a user and convert it into the separate characters' ASCII values, putting them in a list and seperating them by a hyphen. It then adds the user input for 'number' to each seperate ASCII value in the list.

If I input:

python3 stringFunctions.py hideIt hello 6

it should output:

[109-106-113-113-116]

Here is my program:

def cipherIt(word, number):

    vals = []
    for ch in word:
        vals.append(ord(ch))
    new_vals = []
    for val in vals:
        val = str(val   number)
        new_vals.append(vals)
    return new_vals

The output is

[[104,101, 108, 108, 111]],
[[104,101, 108, 108, 111]],
[[104,101, 108, 108, 111]],
[[104,101, 108, 108, 111]],
[[104,101, 108, 108, 111]],
[[104,101, 108, 108, 111]]

When I use: python3 stringFunctions.py cipherIt Hello 6

it puts the ASCII values of "hello" in a list together, but instead of adding five, it prints five instances of the list.

CodePudding user response:

You only need to maintain one list that stores all of the integer values -- using new_vals isn't necessary:

def cipherIt(word, number):
    vals = []
    for ch in word:
        vals.append(ord(ch)   number - 1)
    return '['   '-'.join(str(val) for val in vals)   ']'

print(cipherIt("hello", 6)) # Prints [109-106-113-113-116]

CodePudding user response:

If you are looking to add "number" value to the ord() value then this might be what you want.

def cipherIt(word, number):
    vals = []
    for ch in word:
        vals.append(str(ord(ch)   number))
    text = '-'.join(vals)
    return text

You can, of course, add '[ ]' to the string if that's desired.

text = '['   text   ']'
  • Related