简体   繁体   中英

KeyError python3.7

so I keep getting this error called :

KeyError: 'width'

and I have no idea what to do, I defined what width is, but it still doesn't work.

width = input("For how many characters do you want to align the table?")

then I convert it to an int

width = int(width)

line = ("|  {:^{width}d}  |  {:^{width}b}  |  {:^{width}o}  |  {:^{width}x}")

print(line.format(1))

and when I try to run the programm I get an error.

You have two problems:

  1. width needs to be passed as an argument to format , which doesn't look for variables in the global scope.
  2. You need to pass 1 as an argument for each unlabeled field in the string.

print(line.format(1, 1, 1, 1, width=width))

If you only want to provide 1 once, you need to modify your format string.

# The leading 0 tells each specifier to take its value from the first
# positional argument to `format`.
line = "|  {0:^{width}d}  |  {0:^{width}b}  |  {0:^{width}o}  |  {0:^{width}x}"

print(line.format(1, width=width))

它应该如下

print(line.format(1, 1, 1, 1, width=width))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM