John
John

Reputation: 53

How to resolve an issue with TypeError: unsupported format string passed to numpy.ndarray.__format__

I have the following code, but the output is giving me an error.

possible_rolls = arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
roll_result = np.random.choice(possible_rolls,1,replace=True)
modified_result = roll_result + 11
action_succeeded = modified_result > 15

print("On a modified roll of {:d}, Alice's action {}.".format(modified_result, "succeeded" if action_succeeded else "failed"))

TypeError: unsupported format string passed to numpy.ndarray.format

Upvotes: 0

Views: 4579

Answers (2)

Derek Eden
Derek Eden

Reputation: 4618

you could just use an f-string and access the value of the 1x1 array:

print(f"On a modified roll of {modified_result.item()}, Alice's action {'succeeded' if action_succeeded else 'failed'}.")

sample output:

On a modified roll of 13, Alice's action failed.

Upvotes: 1

marcos
marcos

Reputation: 4510

That's because modified_result is an array, not a number:

possible_rolls = arr = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])
roll_result = np.random.choice(possible_rolls,1,replace=True)
modified_result = roll_result + 11
action_succeeded = modified_result > 15

print(type(modified_result))
>>> <class 'numpy.ndarray'>

This will solve the problem:

print("On a modified roll of {:d}, Alice's action {}.".format(modified_result[0], "succeeded" if action_succeeded else "failed"))

>>> On a modified roll of 13, Alice's action failed.

Upvotes: 0

Related Questions