Converting multiple numbers to letters in python3 - python

I wanted to write a rarther simple cipher program that can convert numbers to letters. So the user provides numbers as input and it gets decoded by the program and that's how you would read the secret message. The problem is that to be able to iterate through numbers i need variable type string and to (add 95 because of ascii codes) i need type int.
i have tried to take input as a string, i have tried converting it to int. I have even tried to convert it in the for loop to an int but i still get an error either that it has to be string or that this variable needs to an int.
a = int(input("Enter a number: "))
for numbers in a:
number = chr(numbers) + 95
print (number)

Your problem seems to be that you need to convert back and forth between different data types: strings, list of strings, and list of integers.
Your question might not be super helpful to others, but I hope this answer will help you at least :) I broke my answer from the comment into shorter steps. Each step has an example of what type of data you are dealing with at the end.
# Read a string like "8 5 12 12 15"
encoded = input("Enter some numbers, separated by spaces: ")
# Turn the string into a list of shorter strings.
# For example: ["8", "5", "12", "12", "15"]
# you should handle input errors here, too
encoded_list = encoded.split(' ')
# Conver the list of strings to a list of integers
# For example: [8, 5, 12, 12, 15]
encoded_numbers = [int(character) for character in encoded_list]
# Decode the numbers and turn them back into strings using chr()
# For example: ["h", "e", "l", "l", "o"]
character_list = [chr(number + 96) for number in encoded_numbers]
# Finally, turn the list of characters into a single string using
# join, then print it
print("Decoded message:")
print("".join(character_list))
I highly recommend playing with the interactive shell (just run python - or even better ipython if you have it installed). It's easier to check what type of data a function returns and experiment with it that way.

Now you're trying to get string and convert it to integer in first string, then you trying to put this integer into for loop.
I do not quite understand what you want from this code, but if you want to type a number of char in ascii ang get this char, use this:
a = input('Enter a number: ')
char = chr(int(a) + 96)
print('Decoded char: ' + char)

You need to iterate over a range of numbers, maybe 26?.
Then you must add 97 which is the ASCII value of a
for number in range(26):
char = f'{chr(number + 97)}'
print (char, end=' ')
output:
a b c d e f g h i j k l m n o p q r s t u v w x y z
From then on, you can easily navigate between the ASCII code and the letter representation; adding an offset modulo 26 will give you a Caesar cypher.
The reverse operation (from letter to ASCII code, to the original (0-26) number is as follows:
ord(char) - 97

Related

How do I check if a string is an integer?

This is my code:
lowMess=input('A\n')
if 'dice(' in lowMess:
diceLen = len(lowMess)
dice = []
for x in range (5,diceLen):
if x.isnumeric():
dice.append(x)
print(dice)
Your x is an integer (taken from range(5, diceLen)) and has nothing to do with the input, other than that it could be used as an index in the input string. So you would want to make that access in the input string:
digit = lowMess[x]
Then continue with the check. As noted in comments, for checking whether a character is a digit, isnumeric is not the right tool. Use isdecimal:
if digit.isdecimal():
...and convert to integer:
dice.append(int(digit))
All this can be done with list comprehension:
dice = [int(digit) for digit in lowMess if digit.isdecimal()]

Convert an integer into a string of its ascii values

Given a number number such that its digits are grouped into parts of length n (default value of n is 3) where each group represents some ascii value, I want to convert number into a string of those ascii characters. For example:
n number Output
==================================
3 70 F
3 65066066065 ABBA
4 65006600660065 ABBA
Note that there is no leading 0 in number, so the first ascii value will not necessarily be represented with n digits.
My current code looks like this:
def number_to_string(number, n=3):
number = str(number)
segment = []
while number:
segment.append(number[:n])
number = number[n:]
return str(''.join('{:0>{}}'.format(chr(segment), n) for segment in number))
Expected outputs:
number_to_string(70)
'F'
number_to_string(65066066065)
'ABBA'
number_to_string(65006600660065, n=4)
'ABBA'
My current code however returns an empty string. For example, instead of 'F' it returns ' '. Any reason why this is? Thank you!
P.S.:
I'm wanting to reverse the process of this question, i.e. turn an integer into a string based on the ascii values of each character (number) in the string. But reading that question is not a requirement to answer this one.
Try this:
import re
def number_to_string(num, n=3):
num_str = str(num)
if len(num_str) < n:
num_str = '0' * (n-len(num_str)) + num_str
elif len(num_str) % n != 0:
num_str = '0'*(n-len(num_str)%n) + num_str
print(num_str)
chars = re.findall('.'*n, num_str)
l = [chr(int(i)) for i in chars]
return ''.join(l)
First pad the given number (converted into string) with required number of zeros, so that it can be evenly split into equal number of characters each. Then using re split the string into segments of size n. Finally convert each chunk into character using chr, and then join them using join.
def numToStr(inp):
"""Take a number and make a sequence of bytes in a string"""
out=""
while inp!=0:
out=chr(inp & 255)+out
inp=inp>>8
print "num2string:", out
return out
does this help?
Is this what you want?
def num_to_string(num, leng):
string = ""
for i in range(0,len(str(num)),leng):
n = str(num)[i:i+2]
string += chr(int(n))
print string
Output:
>>> ================================ RESTART ================================
>>>
>>> num_to_string(650065006600,4)
AAB
>>> num_to_string(650650660,3)
AAB
>>> num_to_string(656566,2)
AAB
>>>
You can just append \x to number as this prints 'p':
print '\x70'

Creating a Caeser program: Converting ASCII to characters

I'm working on python attempting to make a Caeser Cipher program.
So I've made a GUI platform and have been able to make the cipher part work, but it spits out the message only in ASCII.
When you run my program, it takes the info, you say the amount of letters you want the alphabet to shift by, and then says the message in ASCII, how can i get this part to come out in letters?
I tried storing the for loop into a variable then just adding that variable into a common ascii --> character converter, but that doesn't work.
Here's my code:
def encode(userPhrase):
msg = input('Enter your message: ')
key = eval(input("enter a number"))
finalmsg = msg.upper()
for ch in finalmsg:
print( str( ord(ch)+key ), end=' ')
Change your str to chr:
print( chr( ord(ch)+key ), end=' ')
Per the documentation on chr:
Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(957) returns the string 'ν'. This is the inverse of ord().
You need to allow the letters at the end of the alphabet to wrap around to A,B,C... You can do it with modulo arithmetic (complicated), or see the example below
Use chr instead of str. You pass a parameter userPhrase and you ask to enter a message. Also, I suggest using int instead of eval.
def encode(userPhrase):
msg = input('Enter your message: ')
key = int(input("enter a number"))
finalmsg = msg.upper()
for ch in finalmsg:
new_ch = ord(ch)+key
if new_ch > ord('Z'):
new_ch -= 26
print( chr(new_ch), end=' ')
The last problem you have is for non letters (e.g. spaces, etc.)

Difficulty in inserting newline character into Python string after conversion from list form

The code I'm working on takes an input, and is meant to return a "staircase" of hashes and spaces. For instance, if the input was 5, the result should be:
#
##
###
####
#####
I've turned the input into a list of spaces and hashes, and then converted that to a string form, in order to insert \n in every space corresponding to the length of the input (e.g. every 5 characters above). However, my code prints the result in one line. Where am I going wrong??
x = input()
list = []
a = x-1
while a > -1:
for i in range(0, a):
list.append(" ")
for i in range(0, (x-a)):
list.append("#")
a = a - 1
continue
z = str("".join(list))
t = 0
while t<x:
z = z[t:] + "\n" + z[:t]
t = t + x
continue
print str(z)
Start with pseudocode, carefully laying out in clear English what you want the program to do.
Get a number from the user.
Go through each number from 1 until the user's number, inclusive.
On each line, print a certain number of spaces, starting from one fewer than the user's number and going down to zero, inclusive.
On each line, also print a certain number of hash symbols, starting from one and going up to the user's number, inclusive.
Now you can turn that into Python.
First, get a number from the user. It looks like you're using Python 2, so you could use input() or try the safer raw_input() and cast that to int().
num = input()
Going through each number from one until the user's number, inclusive, means a for loop over a range. On Python 2, using xrange() is better practice.
for i in xrange(1, num+1):
This next part will combine steps 3 and 4, using string multiplication and concatenation. For the spaces, we need a number equal to the max number of lines minus the current line number. For the hash symbols, we just need the current line number. You can multiply a string to repeat it, such as 'hi' * 2 for 'hihi'. Finally, the newline is taken care of automatically as the default end character in a Python 2 print statement.
print ' ' * (num-i) + '#' * i
Put it all together and it looks like this:
num = input()
for i in xrange(1, num+1):
print ' ' * (num-i) + '#' * i
As you discovered, achieving the same effect with an intricate structure of counters, nested loops, list operations, and slicing is more difficult to debug. The problems don't stop when you get it working properly, either - such code is difficult to maintain as well, which is a pain if you ever want to modify the program. Take a look at the official Python tutorial for some great examples of clear, concise Python code.
Try this
x = input()
list1 = []
a = x-1
while a > -1:
for i in range(0, a):
list1.append(" ")
for i in range(0, (x-a)):
list1.append("#")
a = a - 1
list1.append("\n")
continue
z = str("".join(list1))
print z

Printing long interger in python up to 10 digits

I am trying to take two long input integers (up to 10 digits) separated by space and display there sum.
I took the input into a string which are separated by space and then split them. After that I type caste them to int.
print "Enter two numbers"
a = raw_input()
a.split(" ")
sum = int(a[0]) + int(a[2])
print "\r", sum
Here I am not able to print the sum if the numbers are of even two digits.
You ignored the return value of str.split():
a.split(" ")
Assign that back to a:
a = a.split(" ")
Python strings are immutable, you cannot split the value of a in-place (let alone replace the type, splitting returns a list object rather than a new string).

Categories

Resources