Appending to the front of for statement output - python

I have this code;
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
print("")
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output = (chr(letter))
print(output,end='')
choice = 0
Output depending on the string something like this;
rc`rcr
qb_qbq
pa^pap
o`]o`o
n_\n_n
m^[m^m
l]Zl]l
k\Yk\k
j[Xj[j
iZWiZi
hYVhYh
gXUgXg
fWTfWf
eVSeVe
dURdUd
cTQcTc
bSPbSb
aROaRa
`QN`Q`
_PM_P_
^OL^O^
]NK]N]
\MJ\M\
[LI[L[
ZKHZKZ
YJGYJY
Now, I need some text before the output for example;
Decryption string rc`rcr
Decryption string qb_qbq
etc...
I have tried;
print("Decryption",output,end='')
and
print("Decryption"+output,end='')
However this gives me that text in front of every letter.
Please assist if you can, and explanation would also be preferred.
Thanks for your time.
Ben

You want to do something like this:
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
word = ""
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output = (chr(letter))
word = word + output
choice = 0
print("Decryption: "+word)
The problem with what you were trying is that it will print the 'Decrypting:' message for each character not for each word, so you need to build the word before printing it.

You are printing the output letter by letter, so adding print("Decryption"+output,end='') will just add the 'Decryption' part to each printout. I suggest doing a:
print("Decryption" + string, end=' ')
before you start your for loop.

You need to build your output string and then print it after the for loop
offset = -0
print ("In Command 3 - Brute force")
string = input("Please enter a string to Brute Force:")
while offset > -26:
offset = offset - 1
output_final = None
for letter in string:
letter = (ord(letter))
letter = letter + offset
if letter > 126:
letter - 95
elif letter < 32:
letter + 32
output_final += (chr(letter))
choice = 0
print 'Description:', output_final

Related

Python Slicing and conditions

I need to write code that can find the middle three characters of a string and print them. If the string is even in length, it would just print the middle two.
If the string is too short, it would print the entire string.
I wrote the following but I get odd results for shorter characters, like the letter "a" for example.
text = input("Type your word: ")
length = len(text)
center = int(length / 2)
print("3 middle letters: ", text[center-1:center+2])
if length % 2 == 0:
print("2 middle letters: ", text[center-1:center+1])
if length <= 1:
print("")
Examples of output:
"a" > too short, print the whole string
"an" > even, return both characters
"can" > odd, return middle three
"cant" > even, return "an"
"canters" > return middle three, "nte"
"cant err" > return middle two, "t "
Looks like you need to review the if statement.
text = input("Type your word: ")
length = len(text)
center = int(length / 2)
if length > 2:
print("3 middle letters: ", text[center-1:center+2])
elif length == 2:
print("2 middle letters: ", text[center-1:center+1])
else:
print("")
text = input("Type your word: ")
length = len(text)
center = length // 2
print(text[center-1:center+1+length % 2])
Note that length // 2 is the same as int(length / 2).

I've tried to create a cipher but it changes the same letter twice

I've got a project for school where I'm supposed to create a cipher where it changes the letters to make a word but when I run it it changes the letter but changes it again as it goes through (like when I put in oTr it's supposed to put out "sea" but instead outputs "oea"). The project is already late so please help. This is what I have at the moment:
decode_length = int(input("Enter a string length to decode: "))
letters = str.lower(input("Enter a string with " + str(decode_length) + " characters: "))
counter = 0
while decode_length > counter:
letters = letters.replace("a", "r")
letters = letters.replace("e", "t")
letters = letters.replace("o", "s")
letters = letters.replace("s", "o")
letters = letters.replace("t", "e")
letters = letters.replace("r", "a")
counter = counter + 1
print(letters)
try this
decode_length = int(input("Enter a string length to decode: "))
letters = str.lower(input("Enter a string with " + str(decode_length) + " characters: "))
replace_dict = {"a":"r",
"e":"t",
"o":"s",
"s":"o",
"t":"e",
"r":"a"}
for character in letters:
letters = letters.replace(character, replace_dict[character])
print(letters)

How do you replace multiple identical characters in a string based on their positions?

So i was making a program for hangman and this is it so far,
word = input("Enter a word: ").upper()
blanks = (len(word)*"_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
blanks = blanks[:word.index(letter)] + letter + blanks[word.index(letter)+1:]
print(blanks)
continue
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have", chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
I was just trying the code out so I would give the word to guess myself, but if I ever gave a word with a letter repeated , like "doggo".
If i gave the letter as "o", it would give out "_ O _ _ _ " instead of " _ O _ _ O" even if i guess "o" again.
Is there anyway I can fix this?
This worked for me:
word = input("Enter a word: ").upper()
blanks = (len(word) * "_")
print(blanks)
chances = 5
while blanks.count("_") > 0:
letter = input("Enter a letter: ").upper()
if len(letter) > 1:
print("Please enter one letter only")
if letter in list(word):
for count, character in enumerate(word):
if letter == character:
blanks = blanks[:count] + letter + blanks[count + 1:]
print(blanks)
else:
chances -= 1
if chances > 0:
print("That letter isn't in the word, you have",
chances, "chance(s) left")
if chances == 0:
print("You lost. The word was", word.lower())
exit()
print("You win! The word was", word.lower())
The difference is that instead of making one replacement we iterate over the word to find all the coincidences and make all the necessary replacements of the same letter.
One solution is to use zip and join in a list compression. zip combines two strings pairwise. The list comprehension steps through the pairs of letters from blanks and word and compares them to the letter. join combines the result - a list of letters - back into a string.
word = "hello"
letter = 'o'
blanks = ''.join([(l if l == letter else b) for b, l in zip(blanks, word)])
#'__ll_'
You can use bytearray and memoryview or list:
# bytearray and memoryview
blank = '_' * 5
print(blank)
fill = 'abcde'
ctr = 0
ba = bytearray(blank, 'utf-8')
mv = memoryview(ba)
while ba.count(b'_') > 0:
mv[ctr] = ord(fill[ctr])
ctr += 1
blank = ba.decode()
print(blank)
Output:
_____
abcde
Second approach, list:
blank = '_____'
print(blank)
blank_list = list(blank)
fill = 'abcde'
while blank_list.count('_') > 0:
blank_list[ctr] = fill[ctr]
ctr += 1
blank = ''.join(blank_list)
print(blank)
Output:
_____
abcde

Text not printing at the end of my for loop for a polyalphabetic cypher

I am making a polyalphabetic cypher. My code is running, but it is not printing the "cyphertext" at the end. I even tried testing individual parts of the for loop and none of it will print either.
import string
alpha = string.ascii_lowercase
message = input('Message:')
message = message.upper()
secretWord = input('Secret word:')
secretWord = secretWord.upper()
cypherText = ''
count = 0
for letter in message:
if letter in alpha:
shift = alpha.index(secretWord[count])
letterIndex = alpha.index(letter)
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count+1
print(cypherText)
Your message is in upper case but alpha is in lower so letter from your iteration over message will never be in alpha
You are also increasing count outside your loop which result in a constant shift
You are making every character uppercase and then you are checking to see if it is a lower case character. As the upper case character isn't a lower case character it doesn't get encrypted.
Use upper or lower case everywhere in your code:
import string
alpha = string.ascii_lowercase
message = input('Message: ').lower()
secret_word = input('Secret word: ').lower()
cypher_text = ''
for i, letter in enumerate(message):
if letter in alpha:
shift = alpha.index(secret_word[i]) if len(secret_word) > i else alpha.index(secret_word[0])
letter_index = alpha.index(letter)
cypher_letter = alpha[(letter_index + shift) % 26]
cypher_text = cypher_text + cypher_letter
print(cypher_text)
Output:
Message: animal
Secret word: snake
saiwed

Python converting letter to ASCII using ord

I am trying to do some coursework but I have hit a wall. I am trying to write a function that takes a letter and a digit as the inputs, and returns the letter shifted key positions to the right in the alphabet.
This is what I have so far:
def code_char(c,key):
letter=input("Enter letter to be moved")
shift=int(input("Enter degree of shift"))
letter=ord(letter)
if letter>=65 and letter <=90:
letter=letter+shift
while letter>90:
letter=letter-26
elif letter>=97 and letter <=122:
letter=letter+shift
while letter>122:
letter=letter-26
letter=chr(letter)
print(letter)
code_char("",0)
The problem is the letter=ord(letter) as I keep getting TypeError: ord() expected string of length 1, but list found. I have tried different variations.
I need to convert the input 'letter' into ASCII.
As suggested by Willem in the OP comments, input() is giving you a str containing the letter and the new-line char \n, use .strip() to solve it if you are using an old Python version:
def code_char():
letter = ord(input("Enter letter to be moved").strip())
shift = int(input("Enter degree of shift"))
if (letter >= 65) and (letter <= 90):
letter += shift
while (letter > 90):
letter -= 26
elif (letter >= 97) and (letter <= 122):
letter += shift
while letter > 122:
letter -= 26
print(chr(letter))
code_char()
New Python versions (e.g. 3.6.0) should not need the .strip() part, being your code after the formatting edit I did working perfectly:
def code_char():
letter = ord(input("Enter letter to be moved"))
shift = int(input("Enter degree of shift"))
if (letter >= 65) and (letter <= 90):
letter += shift
while (letter > 90):
letter -= 26
elif (letter >= 97) and (letter <= 122):
letter += shift
while letter > 122:
letter -= 26
print(chr(letter))
code_char()

Categories