1import string
2
3import numpy as np
4
5from pandas._typing import NpDtype
6
7RANDS_CHARS = np.array(list(string.ascii_letters + string.digits), dtype=(np.str_, 1))
8
9
10def rands_array(nchars, size, dtype: NpDtype = "O", replace: bool = True) -> np.ndarray:
11 """
12 Generate an array of byte strings.
13 """
14 retval = (
15 np.random.choice(RANDS_CHARS, size=nchars * np.prod(size), replace=replace)
16 .view((np.str_, nchars))
17 .reshape(size)
18 )
19 return retval.astype(dtype)
20
21
22def rands(nchars) -> str:
23 """
24 Generate one random byte string.
25
26 See `rands_array` if you want to create an array of random strings.
27
28 """
29 return "".join(np.random.choice(RANDS_CHARS, nchars))