简体   繁体   中英

format a string to a list in python

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

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.

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:

You can solve this using lambda functions.

num = list(map(lambda x: int(float(x)), s.strip("[]").split()))

Here, s.strip("[]") remove the square brackets. We use lambda functions to convert all float to int .

We use int(float(x)) instead of int(x) because otherwise we get ValueError when we are converting "2153." to int .

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