Swap upper and lower case with its ASCII value - python

Im trying to swap letter type with its ASCII value however I am only getting the last word of the string as an output. it also will not accept any string with number values
def get_sentence():
sentence = input("Please input the sentence:")
words = sentence.split(' ')
sentence = ' '.join(reversed(words))
return sentence
ans = ''
def main():
sentence = get_sentence()
ans =''
for s in sentence:
if ord(s) >= 97 and ord(s) <= 122:
ans = ans + chr(ord(s) - 32)
elif ord(s) >= 65 and ord(s) <= 90 :
ans = ans + chr(ord(s) + 32)
else :
ans += ' '
print(ans)
if __name__ == "__main__":
main()

I am not sure if this is the result you want (adding expected output would be helpful next time) but removing the print statement outside the for loop seems to fix it for me.
def get_sentence():
sentence = input("Please input the sentence:")
words = sentence.split(' ')
sentence = ' '.join(reversed(words))
return sentence
ans = ''
def main():
sentence = get_sentence()
ans =''
for s in sentence:
if ord(s) >= 97 and ord(s) <= 122:
ans = ans + chr(ord(s) - 32)
elif ord(s) >= 65 and ord(s) <= 90 :
ans = ans + chr(ord(s) + 32)
else :
ans += ' '
print(ans) # this should be outside!
if __name__ == "__main__":
main()

There's a simpler way to do this, using built-in methods isupper() and islower(). Then you don't need to handle sentences (or punctuation) separately.
def swap_case(sentence: str) -> str:
letters = (
letter.upper() if letter.islower() else letter.lower()
for letter in sentence
)
return "".join(letters)
print(swap_case(get_sentence()))
Notice my function also returns the result rather than printing it. And it takes input of the sentence, so you can use it in other cases, which makes it more reusable. Not sure why you want the words of the sentence reversed... but ¯\_(ツ)_/¯

Related

How do I return my output instead of print?

def spin_words(sentence):
adjusted_string = sentence.split()
for i in adjusted_string:
if len(i) > 5:
print(i[::-1], end = ' ')
else:
print(i, end = ' ')
The problem is asking to take a string and return the same string but, with all the five letter words or more in reversed
def spin_words(sentence):
splitted_string = sentence.split()
reversed_fives = [s[::-1] if len(s) >= 5 else s for s in splitted_string]
return " ".join(reversed_fives)

Encoding a password with special characters

I am in an into to Programming class and the assignment is in part to shift the letters of a valid password by +1 if it is a letter or number and -1 if it is a !##$ special character. I have most of it working with my below code but I always get the wrong output for the special characters. If I use to the code of anything high like 128 then I get the wrong symbol.
I am using the code from an encryption program from the other week and slowly changing things but I feel like this is too involved for something simple
If I enter the password UMA#augusta2020 I need to get the output VNB?bvhvtub3131 but I either end up with a space, b, or wrong symbol when I change the code input between 26,64,96,128, etc.
I have updated the code to fix small errors
def main():
print("This program validates and encrypts a password")
print()
main()
# The Encryption Function
def cipher_encrypt(plain_text):
encrypted = ""
for c in plain_text:
if c.isupper(): #check if it's an uppercase character
c_index = ord(c) - ord('A')
# shift the current character by key positions
c_shifted = (c_index + 1) % 26 + ord('A')
c_new = chr(c_shifted)
encrypted += c_new
elif c.islower(): #check if its a lowecase character
c_index = ord(c) - ord('a')
c_shifted = (c_index + 1) % 26 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
elif c.isdigit():
# if it's a number,shift its value
c_new = (int(c) + 1) % 10
encrypted += str(c_new)
else:
# if its neither alphabetical nor a number, -1
c_shifted = (c_index - 1) % 128 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
return encrypted
plain_text =input("Enter your Password: ")
print()
ciphertext = cipher_encrypt(plain_text)
print()
print("Your Password: ", plain_text)
print()
print("Your password is valid and encrypted it is: ", ciphertext)
print()
Here is a much cleaner approach:
def cipher_encrypt(plain_text):
alpha = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
puncs = '!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
encrypted_text = ''
for c in plain_text:
if c.lower() in alpha:
c_index = alpha.index(c.lower())
e_index = (c_index + 1)%len(alpha)
if c == c.lower():
encrypted_text += alpha[e_index]
else:
encrypted_text += alpha[e_index].upper()
elif c in digits:
c_index = digits.index(c)
e_index = (c_index + 1)%len(digits)
encrypted_text += digits[e_index]
else:
c_index = puncs.index(c)
e_index = (c_index +len(puncs) - 1)%len(puncs)
encrypted_text += puncs[e_index]
return encrypted_text
In this approach I deal with each caharcter in plain text by:
Determining idf the char is part of alpha by making use of the c.lower() function to isolate alpha chars and then find an index modulo the len of alpha. Then I determine if I need an uppercase char or lower case in the encrypted text.
I use the same modulo approach for digits, but don't have to worry about upper and lower, finally
I find the index for the punctuations found in the plain_text

Python brute force decryption just with ASCII character set from 32-126 (printable)

Hi all, having immense trouble here and can't figure out where errors are so seeking assistance. I've > pasted my two (best? closest?) attempts below.
I'm attempting a brute-force approach to decryption, but not using just the usual 26 characters of the > alphabet. The intent is to encapsulate the full set of printable characters from ASCII 32 to ASCII 126.
If I can get this written correctly, it should print out a result at the bottom of this post.
Where am I going wrong?
input_string = input('Enter code for decryption: ')
input_list = list(input_string)
shift_value = 0
decryption_index = 0
while shift_value in range(1, 95, 1) :
while decryption_index < len(input_list):
decryption_index = 0
shifter = (ord(input_list[decryption_index]) - ord(" ") - shift_value) % 95
chr_decrypt = chr(ord(input_list[decryption_index]) + shift_value)
input_list[decryption_index] = chr_decryption
decryption_index += 1
shift_value -= 1
input_string = ''.join(input_list)
print ('Shift value',shift_value,' = Decrypted code:' ,input_string)
&...
input_string = input('Please enter code for decryption: ')
input_list = list(input_string)
shift_value = 0
decryption_index = 0
for shift_value in range(1, 95, 1):
for decryption_index in range(len(input_list)):
shifting = (ord(input_list[decryption_index]) - ord(" ") - shift_value) % 95
chr_decryption = chr(shift_value + ord(" "))
input_list[decryption_index] = chr_decryption
decryption_index += 1
input_string = ''.join(input_list)
print('Shift value', shift_value, '= Decrypted code:', input_string)
Example intended output:
Shift value 1 = Decrypted code: xjhwjy%xvznwwjq
(through to)
Shift value 94 = Decrypted code: zljyl{'zx|pyyls
However, I get only:
Shift value 94 = Decrypted code: ~~~~~~~~~~~~~~~
or a blank.
Update as requested; method used to encrypt is:
input_string = input("Please enter string to encrypt: ")
shift_value = int(input("Please enter shift value (1 to 94): "))
total = ""
for char in input_string:
x = ord(char)
x = x + shift_value
while x < 32:
x += 95
while x > 126:
x -= 95
total += chr(x)
print("")
print("Encrypted string:")
print(total)
If you use bruteforce for decryption there is no way you can check which one is correct output. So you need to useshift_value to decrypt the string.
def decrypt(s, key):
ans = ''
for char in s:
x = (ord(char) - ord(' ') - key) % 95
ans += chr(x + ord(' '))
return ans
decrypt('xjhwjy%xvznwwjq', 93) #zljyl{'zx|pyyls
And one more thing In your encryption code you are using while loop to change x value. Loop is not required for this. You can just use if condition.
def encrypt(s, key):
ans = ''
for char in s:
x = ord(char) + key
if x < 32:
x += 95
if x > 126:
x -= 95
ans += chr(x)
return ans
encrypt("zljyl{'zx|pyyls", 93) #xjhwjy%xvznwwjq

How can I make this code shorter (less lines etc)

I am writing a code and want to make it as short as possible, is there any way i can?
text = raw_input("Give me some text > ")
list1 = []
for char in text:
num = ord(char)
if num in range(48,57):
print "ERROR 319: Number entered"
quit()
elif num in range(65,90) or num in range (97,122):
upper = char.upper()
list1.append(upper)
num1 = 0
vowelCount = 0
conCount = 0
for x in range(len(list1)):
if list1[num1] == "A" or list1[num1] == "E" or list1[num1] == "I" or list1[num1] == "O" or list1[num1] == "U":
vowelCount = vowelCount + 1
else:
conCount = conCount + 1
num1 = num1 + 1
print "Vowels: " +str(vowelCount) + " Consonants: " + str(conCount)
Instead of taking ord() of the character, you can use the string methods:
char.isdigit() # check if a char is a digit
char.isalpha() # check if char is letter
For checking the vowel counts, try:
vowel_count = len(filter(lambda c: c in "aeiou", list1))
cons_count = len(list1) - vowel_count
Building off of AmourK's answer, you could do something like this:
text = raw_input("Give me some text > ")
vowel_count = len(filter(lambda c: c in "aeiou", text))
cons_count = len(filter(lambda c: c not in "aeiou" and c.isalpha(), text))
print "Vowels: %d Consonants: %d" % (vowel_count, cons_count)

Encrypt message using recursion, python

I need to write a recursive function to encrypt a message by
converting all lowercase characters to the next character (with z transformed to a) in python.
This is my code so far, but I don't know how to go farther, or how to correct the error.
sentence = input("Enter a message: \n")
letter_number = 0
def encrypt_sentence (s, number):
if letter_number == len(sentence) - 1:
return(s)
else:
if s[letter_number] == chr(122):
return encrypt_sentence(chr(ord(s[letter_number])-25), letter_number + 1)
else:
return encrypt_sentence(chr(ord(s[letter_number])+1), letter_number + 1)
print("Encrypted message")
print(encrypt_sentence(sentence, letter_number))
I've fixed your code and now it works.
sentence = input("Enter a message: \n")
letter_number = 0
def encrypt_sentence (sentence):
if sentence:
if sentence == chr(122):
return chr(ord(sentence[letter_number])-25)
else:
return chr(ord(sentence[letter_number])+1)
print("Encrypted message")
ris = ''
for word in sentence:
ris += encrypt_sentence(word)
print(ris)

Categories