I'm trying to print the cipher text on the same line. When I run the program now all the characters get printed on to the next line. How do I do this?
#!/usr/bin/env python3
import cs50
import sys
def main():
if len(sys.argv) != 2:
print('caesar.py k')
exit(1)
k = int(sys.argv[1])
print('plaintext: ', end = '')
s = cs50.get_string()
print('ciphertext: ', end = '')
for i in range(len(s)):
c = s[i]
if str.isupper(c):
cipher = (((ord(c) - 65) + k) % 26) + 65
print(chr(cipher))
elif str.islower(c):
cipher = (((ord(c)- 97) + k) % 26) + 97
print(chr(cipher))
else:
print(chr(c))
exit(0)
if __name__ == "__main__":
main()
The error comes from
c - chr(65)
If you look at the type of chr(65)
it's actually a string.
>>> type(chr(65))
str
The TypeError you're getting is just telling you that you can't subtract a string from another string.
You might want to look at using ord
instead which returns an integer representing the Unicode code point of a character.
Furthermore
for i in range(len(s)):
c = s[i]
Is a python anti-pattern and can be simplified wth just
for c in s:
print(c) # c is your character
Since s is an iterable
No worries, I answered this. I added a end = ''
at the end of the print statements.
I think @Jack Evans is the best style to go. However, for your interest I've made some modifications to help answer your question (hopefully):
#!/usr/bin/env python3
import cs50
import sys
def main():
if len(sys.argv) != 2:
print('caesar.py k')
exit(1)
k = int(sys.argv[1])
print('plaintext: ', end = '')
s = cs50.get_string()
print(s)
print('ciphertext: ', end = '')
for i in range(len(s)):
c = s[i]
if str.isupper(c):
cipher = (((ord(c) - 65) + k) % 26) + 65
print(chr(cipher), end= '')
elif str.islower(c):
cipher = (((ord(c)- 97) + k) % 26) + 97
print(chr(cipher), end= '')
else:
print(chr(c), end= '')
print()
exit(0)
if __name__ == "__main__":
main()
Here is the example output if someone executed the script as:
./name_of_file 3
with the string being:
howdy
The result would be:
plaintext: howdy
ciphertext: krzgb
To answer you question directly, to have the print cipher characters print on the same line just change:
print(chr(cipher))
to
print(chr(cipher), end= '')
In Python, using print() without specifying how print should end it will automatically end with a newline. As you can see in the version I provided, you can use this idea to easily incorporate newlines.
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.