从元组打印索引时,Python添加新行

时间:2019-07-04 20:58:43

标签: python python-3.x tuples

我正在尝试在同一行上从两个独立的元组打印两个独立的索引。但是当我使用f字符串打印时,它会将我打印的第二个索引放在新行上。

无论如何尝试,似乎都无法弄清楚,它总是在新行上打印姓氏。

surnames = tuple(open("Surnames.txt", "r"))
first_names_male = tuple(open("Male_names.txt", "r"))
first_names_female = tuple(open("Female_names.txt", "r"))

print(f"{first_names_male[0]} {surnames[0]}")

应全部打印出“ David Smith”

相反,它在第一行显示大卫,然后在下一行显示空格,然后是史密斯

2 个答案:

答案 0 :(得分:1)

您可以使用如下代码从文件中每行的末尾删除新行并显式关闭文件:

with open("Surnames.txt", "r") as f:
    surnames = f.read().splitlines()
with open("Male_names.txt", "r") as f:
    first_names_male = f.read().splitlines()
with open("Female_names.txt", "r") as f:
    first_names_female = f.read().splitlines()

print(f"{first_names_male[0]} {surnames[0]}")

或者如果您愿意,可以这样:

with open("Surnames.txt", "r") as f:
    surnames = map(str.rstrip, f)
    # or
    surnames = [r.rstrip('\n') for r in f]

有关更多选项,请参见https://stackoverflow.com/a/12330535/3830997

答案 1 :(得分:0)

这样可以更好地处理文件,因为它还会关闭文件并从每行末尾删除换行符。

def func(filename):
    line_list = []

    with open(filename) as f:
        for line in f:
            line = line.strip()
            if len(line) > 0:
                line_list.append(line)

    return line_list


if __name__ == '__main__':
    surnames_list = func('Surnames.txt')
    male_names_list = func('Male_names.txt')
    female_names_list = func('Female_names.txt')

    print(f"{male_names_list[0]} {female_names_list[0]}")

这能给您想要的结果吗?