So I was trying to print some formated text printing the name and distance of objects in space that are close to the earth using the nasa api.
My problem is that i can't manage to get empty spaces in front of the distance, (so that they are justified right, next to the name) I tried {:25d} but thats not working and giving me the
error: print(f"Name: {name:25} Entfernung km: {distance:25d}") ValueError: Unknown format code 'd' for object of type 'str'
The python documentation example(https://docs.python.org/3/tutorial/inputoutput.html) is working without a problem.
import requests
key = "DEMO_KEY"
start_date = "2021-03-20"
end_date = "2021-03-27"
r = requests.get(f"https://api.nasa.gov/neo/rest/v1/feed?start_date={start_date}&end_date={end_date}&api_key={key}")
json = r.json()
def search_name_distance(date):
print(date, ":\n")
for x in range(len(json['near_earth_objects'][date])):
name = json['near_earth_objects'][date][x]['name']
distance = json['near_earth_objects'][date][x]['close_approach_data'][0]['miss_distance']['kilometers']
print(f"Name: {name:25} Entfernung km: {distance:25d}")
print("\n\n")
search_name_distance(start_date)
'''
working:
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print(f'{name:10} ==> {phone:10d}')
'''
CodePudding user response:
d
is for an integer, but in your case distance
is a str
. So you can convert
distance = int(json['near_earth_objects'][date][x]['close_approach_data'][0]['miss_distance']['kilometers'])