[英]How do I print the characters on the same line?
我正在嘗試在同一行上打印密文。 現在,當我運行程序時,所有字符都被打印到下一行。 我該怎么做呢?
#!/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()
錯誤來自
c - chr(65)
如果您查看chr(65)
的類型,它實際上是一個字符串。
>>> type(chr(65))
str
您收到的TypeError只是告訴您不能從另一個字符串中減去一個字符串。
您可能想看看使用ord
代替,它返回一個表示字符的Unicode代碼點的整數。
此外
for i in range(len(s)):
c = s[i]
是python反模式,可以簡化為
for c in s:
print(c) # c is your character
由於s是可迭代的
不用擔心,我回答了。 我在打印語句的末尾添加了end = ''
。
我認為@Jack Evans是最好的選擇。 但是,為了您的利益,我進行了一些修改以幫助回答您的問題(希望如此):
#!/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()
如果有人按以下方式執行腳本,則輸出示例如下:
./name_of_file 3
字符串為:
howdy
結果將是:
plaintext: howdy
ciphertext: krzgb
要直接回答您的問題,只需將打印密碼字符打印在同一行即可:
print(chr(cipher))
至
print(chr(cipher), end= '')
在Python中,使用print()而不指定應如何結束打印,它將自動以換行符結尾。 正如您在我提供的版本中看到的那樣,您可以使用此想法輕松合並換行符。
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.