python 3 : Print multiple lines to one line

标签 python python-3.x

我已经使用 Google 机器在 Stackoverflow 和其他网站上搜索过线程,但没有找到我正在寻找的东西。

我是使用 Python 3 的新编程学生,所以我的大部分东西都非常基础。

我正在编写一个允许我使用 Caeser 密码加密和解密文本文件的程序。从用户那里获取短语并应用用户给定的转变。

这就是我现在正在使用的:

一些代码只是作为占位符放在那里,直到我进一步了解我的程序。

import string
print ("1) Encrypt")
print ("2) Decrypt")
print ("3) Decrypt w/o Shift")

Choice = input("Choice: ")

if Choice == '1':
    message = input("Message: ")
    shift = int(input("Shift: "))
    newmsg = ''
    for char in message:
        if char.isupper():
            new = (ord(char)-ord('A')) + shift
            newmsg = chr(new+ord('A'))
            print (newmsg, end="")
        else:
            print(" ")


elif Choice == '2':
    print ("2")

elif Choice == '3':
    print ("3")

当我输入一个测试短语时,例如“THIS IS A TEST”,它会给我输出,使用正确的加密,但它显示如下:

V
J
K
U

K
U

C

V
G
U
B

这是 2 的“移位”

如果我将 end = ' ' 添加到我的 print 语句中,它的输出为:

V J K U
K U
C
V G U V

如果我将 end = '' 添加到我的打印语句中,它的输出为:

VJKU
KU
C
VGUV

我正在寻找输出:

VJKU KU C VGUV

我知道这是我忽略的愚蠢行为。任何帮助,将不胜感激。非常感谢。

最佳答案

使用end="",还要在行中加上这个参数

print(" ")

否则,这一行将添加一个换行符。

也就是说,您最好先收集列表中的字符,然后只调用一次 print():

print("".join(list_of_characters))

另一种方法是使用 str.maketrans() 创建字符转换表并使用 str.translate() 应用它。

关于 python 3 : Print multiple lines to one line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451461/

相关文章:

python - 在Python中,检索Xml属性值

python - 我怎样才能从这段代码中省略 <h> 标签?

python - 将嵌套列表转换为python中的字典

python - 如何使用 Python 3 仅使用内置模块上传大文件?

python - Flask celery 应用程序与普通 Flask 应用程序(如何使它们同时工作)

python - 使用 dateutil.parser 解析不完整日期时,如何将日期设置为 1?

python - Runtime.ImportModuleError : Unable to import module 'lambda_function' : No module named 'httplib2'

python - Excel中3色条件格式的RGB和HEX代码是什么?

python - 如何使用 python 从 JSON 中提取特定字段和值?

python - 反向和 [::-1] 之间的区别