【问题标题】:How do I remove the last newline character in a text in Python?如何在 Python 中删除文本中的最后一个换行符?
【发布时间】:2016-05-03 14:50:27
【问题描述】:

我有一个程序可以解码凯撒密码和一些包含多行要解码的文本文件。

根据我的讲师代码检查器,文本后面总是有一个空行,但我自己运行代码时什么也没看到。

删除最后一个字符只会删除文本中的最后一个字母或数字,而不是换行符。

这是我的代码:

import sys
import string
import collections

ciphertext_lines = sys.stdin.readlines()
ciphertext = ''

for i in ciphertext_lines:
    ciphertext += i

alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'



def getShiftVal():

    string = ''

    for line in ciphertext:
        string = string + line

    most_common_letter = ((collections.Counter(string).most_common(2)[1])[0])

    shift_val = (alphanum.index(most_common_letter) - 4)

    return shift_val



def decrypt(ciphertext, n):

    alphabet_numbers = collections.deque(string.ascii_uppercase + string.digits)

    alphanum = ''.join(list(alphabet_numbers))

    alphabet_numbers.rotate(n)

    alphanum_rotated = ''.join(list(alphabet_numbers))

    return ciphertext.translate(str.maketrans(alphanum, alphanum_rotated))



def main():

    n = getShiftVal()

    decrypted = decrypt(ciphertext, n)

    print(decrypted)

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python newline strip blank-line


    【解决方案1】:

    print 默认在其输出后添加一个换行符。在 Python 2 下,使用 print decrypted,(注意尾随逗号)来抑制尾随换行符。在 Python 3 下,使用print(decrypted, end='')。或者,您也可以直接使用sys.stdout.write(decrypted) 编写输出而不进行任何格式化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      相关资源
      最近更新 更多