最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

numpy ndarray - How to reduce verbosity of self-documenting expressions in Python f-strings? - Stack Overflow

programmeradmin1浏览0评论

This script:

import numpy as np

a = np.array([2, 3, 1, 9], dtype='i4')
print(a)
print(f'{a=}')

produces:

[2 3 1 9]
a=array([2, 3, 1, 9], dtype=int32)

Is there a way to get just a=[2 3 1 9] from {a=} f-string as in the standard formatting in the first line?

This script:

import numpy as np

a = np.array([2, 3, 1, 9], dtype='i4')
print(a)
print(f'{a=}')

produces:

[2 3 1 9]
a=array([2, 3, 1, 9], dtype=int32)

Is there a way to get just a=[2 3 1 9] from {a=} f-string as in the standard formatting in the first line?

Share Improve this question asked Feb 6 at 5:22 Paul JurczakPaul Jurczak 8,1654 gold badges51 silver badges96 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 4

By default, = f-string syntax calls repr on the thing to be formatted, since that's usually more useful than str or format for the debugging use cases the = syntax was designed for.

You can have it apply normal formatting logic instead by specifying a format - even an empty format will do, so this would work:

print(f'{a=:}')

or you can explicitly say to call str with !s:

print(f'{a=!s}')

You can use custom Numpy formatting and array to string convertion, like this:

import numpy as np

a = np.array([2, 3, 1, 9], dtype='i4')
print(f'a={np.array2string(a, separator=" ")}')
发布评论

评论列表(0)

  1. 暂无评论