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



我正在尝试从同一行上的两个单独的元组打印两个单独的索引。但是,当我使用f-string打印时,它将第二个索引我打印在新系列上。

无论我尝试什么,似乎都无法弄清楚它总是在新的姓氏上打印。

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

应该在一行上打印出"大卫·史密斯"

相反,它在第一行上显示大卫,然后在下一行上有一个空间,然后史密斯

您可以使用这样的代码从文件中的每一行末尾删除新行,并明确关闭文件:

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

这将是对文件的更好处理,因为它也关闭文件并从每行末尾删除新线。

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

这会给您带来所需的结果吗?

最新更新