#python #readfile
#python #readfile
Вопрос:
Мне нужно, чтобы мой вывод выглядел красиво, и это выглядит очень неаккуратно.
———Текущий вывод———
Below are the players and their scores
John Doe 120
Sally Smooth 115
———-Завершение текущего вывода———-
Мой желаемый результат следует
——- Желаемый результат——————
Below are the players and their scores
John Doe 120
Sally Smooth 115
———Завершить желаемый результат————-
мой текущий код следующий;
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
print("Below are the players and their scores")
print()
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('n')
score = score.rstrip('n')
# prints the names and scores
print(name " " score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
main()
Ответ №1:
Попробуйте использовать символ табуляции, чтобы лучше форматировать пробелы.
print(name "t" score)
Это должно дать вам что-то более близкое к желаемому результату. Но вам может потребоваться использовать два, если некоторые имена длинные.
Комментарии:
1. Ниже приведены игроки и их оценки Джон Доу 120 Салли Смут 115 >>>
2. В качестве запоздалой мысли вы также можете попробовать установить и использовать «tabulate», что даст вам более качественный результат без необходимости вручную вычислять размеры имен. 🙂
Ответ №2:
Вы можете добавить имена и оценки в список, а затем распечатать его в виде таблицы как
import numpy as np
name_list = ['jane doe' ,'sally smooth']
score = np.array([[102,],[106,]]) #make a numpy array
row_format ="{:>15}" * (len(name_list))
for name, row in zip(name_list, score):
print(row_format.format(name, *row))
Примечание: Это зависит от str.format()
Этот код выведет:
jane doe 102
sally smooth 106