【问题标题】:Printing to a single line打印到单行
【发布时间】:2017-03-15 00:23:01
【问题描述】:

我正在做一个 python 项目,最近完成了一项任务,但有一个小例外。最后一部分是打印一个字符串,在我的一生中,它一直在多行上打印。

我不想以任何方式作弊,但是有人可以帮我找到最终打印到 1 行的解决方案吗?

import random

def loadFile(fileName):
    file_variable = open(fileName, 'r')
    stringList = file_variable.readlines()
    file_variable.close()
    return stringList


def main():
    list_1 = loadFile('names.txt')
    list_2 = loadFile('titles.txt')
    list_3 = loadFile('descriptors.txt')

print(random.choice(list_2), random.choice(list_1), random.choice(list_1), ' the ', random.choice(list_3))

main()

【问题讨论】:

    标签: python string file-io


    【解决方案1】:

    file.readlines() 返回包含换行符的行列表。 您需要使用 str.stripstr.rstrip 从字符串中删除换行符:

    print(
        random.choice(list_2).rstrip(),  # rstrip('\n') if you want keep trailing space
        random.choice(list_1).rstrip(),
        random.choice(list_1).rstrip(),
        'the',
        random.choice(list_3).rstrip()
    )
    

    或通过更改loadFile:

    def loadFile(fileName):
        with open(fileName) as f:
            return [line.rstrip() for line in f]
    

    【讨论】:

    • @Rivers31334,不客气。快乐的 Python 编程!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多