I have a string formatted as:
s = "[2153. 3330.75]"
I'd like to convert to a list with ints
.
Expected output: l = [2153, 3330]
type(l)
is list
CodePudding user response:
The following code does what you are looking for.
l = [int(float(x)) for x in s.strip('[]').split()]
The float conversion is required because strings containing "." cannot be converted directly to integers.
CodePudding user response:
The string looks like a numpy array.
First, we convert the string to a float numpy array using numpy fromstring
method. Then convert the float array to int
array using astype
method. Finally, convert the numpy array to a list
using tolist
method:
import numpy as np
s = "[2153. 3330.75]"
values = np.fromstring(s[1:-1], dtype=float, sep=' ').astype(int).tolist()
print(values)
Output:
[2153, 3330]
References: