简体   繁体   English

Python 3:将多行打印到一行

[英]Python 3: Print multiple lines to one line

I have searched through threads on Stackoverflow and other sites using the Google machine and nothing gives me quite what I am looking for. 我已经使用谷歌机器搜索了Stackoverflow和其他网站上的线程,没有什么能让我得到我想要的东西。

I am new programming student using Python 3 so most of my stuff is pretty basic. 我是使用Python 3的新编程学生,所以我的大多数东西都非常基础。

I am writing a program that allows me to encrypt and decrypt a text file using the Caeser cipher. 我正在编写一个程序,允许我使用Caeser密码加密和解密文本文件。 Taking a phrase from the user and applying a user given shift. 从用户处获取短语并应用给定班次的用户。

This is what I am working with right now: 这就是我现在正在使用的:

Some of the code is just in there as a place holder until I get further along into my program. 有些代码就在那里作为占位符,直到我进一步深入到我的程序中。

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")

When I input a test phrase, such as "THIS IS A TEST", it gives me the output, with the correct encryption, but it displays it like this: 当我输入一个测试短语,例如“这是一个测试”时,它会给我输出,加密正确,但它显示如下:

V
J
K
U

K
U

C

V
G
U
B

This is with a "shift" of 2 这是“转移”2

If I add end = ' ' to my print statement, it outputs as: 如果我在我的print语句中添加end = ' ' ,则输出为:

V J K U
K U
C
V G U V

If I add end = '' to my print statement, it outputs as: 如果我在我的print语句中添加end = '' ,则输出为:

VJKU
KU
C
VGUV

I am looking for an output of: 我正在寻找一个输出:

VJKU KU C VGUV

I know this is something silly that I am overlooking. 我知道这是愚蠢的,我在俯视。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank you much. 非常感谢你。

Use end="" , but also add this parameter to the line 使用end="" ,但也将此参数添加到该行

print(" ")

Otherwise, this line will add a newline. 否则,此行将添加换行符。

That said, you are probably better off with first collecting the characters in a list, and calling print() only once: 也就是说,你可能最好先收集列表中的字符,然后只调用print()一次:

print("".join(list_of_characters))

Yet another approach would be to create a character translation table with str.maketrans() and apply it with str.translate() . 另一种方法是使用str.maketrans()创建一个字符转换表,并将其应用于str.translate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM