String Formatting (ValueError: Unknown format code 'd' for object of type 'str')

String Formatting (ValueError: Unknown format code 'd' for object of type 'str')

所以我试图打印一些格式化文本,打印 space 中靠近地球的物体的名称和距离,使用美国宇航局 api。

我的问题是我无法设法在距离前面留空 spaces,(以便它们在名称旁边正确对齐)我试过 {:25d} 但就是这样不工作并给我

error: print(f"Name: {name:25} Entfernung km: {distance:25d}") ValueError:'str'

类型对象的未知格式代码 'd'

python 文档示例 (https://docs.python.org/3/tutorial/inputoutput.html) 工作正常。

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}')
'''

d 用于整数,但在您的情况下 distancestr。所以你可以转换

distance = int(json['near_earth_objects'][date][x]['close_approach_data'][0]['miss_distance']['kilometers'])