Python printing format in a for loop

Viewed 53
*if menuInput == '1':
     print("")
     encryptString = input("Please enter string to encrypt:")
     print("")
     offSetValue = int(input("Please enter offset value (1-94):"))
     print("")
 
     for character in encryptString:
         x = ord(character)
         y = x + offSetValue
         z = chr(y)      
         print("Encrypted string:") 
         print(z)*

I want the string that has been encrypted to be outputted in this format:

Encrypted string:

abcde 

but it comes out in this format:

Encrypted string: 
a
Encrypted string: 
b
Encrypted string: 
c
Encrypted string: 
d

I've tried using end and sep but they don't help.

3 Answers

I think this is what you want.

print("")
encryptString = input("Please enter string to encrypt:")
print("")
offSetValue = int(input("Please enter offset value (1-94):"))
print("")

print("Encrypted string:") 
for character in encryptString:
    x = ord(character)
    y = x + offSetValue
    z = chr(y)      
    print(z, end="")

print()

You want print("Encrypted string:") before the loop and use end instead of sep. sep is used to separate multiple arguments in the print. end is the terminating character(s) added to the end of what is printed. Here we terminate with the empty string. The default for end is the newline character, \n. That is why you saw everything printed on a new line.

By using fernet, it allows you to encrypt messages more securely than shifting the position of characters in the string.

from cryptography.fernet import Fernet
if menuInput == '1':
    print()
    encryptString = input("Please enter string to encrypt:")
    print()
    key = Fernet.generate_key()
    fernet = Fernet(key)
    encryptedString = fernet.encrypt(encryptString.encode())
    print("Encrypted string:", encryptedString)

Here we go.

if menuInput == '1':
 print("")
 encryptString = input("Please enter string to encrypt:")
 print("")
 offSetValue = int(input("Please enter offset value (1-94):"))
 print("")

 print("Encrypted string:") 
 for character in encryptString:
     x = ord(character)
     y = x + offSetValue
     z = chr(y)      
     print(z, end='')
Related