简体   繁体   中英

How to convert a string to a Python array?

I have a string looks like this:

"[3 3 3 3 4 3 4 ...]"

And I need to convert this to a python array. Should I add , after every number before doing anything? or

Is this possible? If so how?

Is this what you want?

dd = "[3 3 3 3 4 3 4]"
new_dd = dd.replace('[','').replace(']','').split(' ')
# ['3', '3', '3', '3', '4', '3', '4']
# if you want to convert int.

[int(d) for d in new_dd]
# [3, 3, 3, 3, 4, 3, 4]

Yes, you can use the.split() function. Simply do:

string = "..." # The string here
numbers = string[1:-1].split() # We have the 1:-1 here because we want to get rid of the square brackets that are in the string.

But if you want a list of integers (int) rather than an array of strings, then you need:

s = "[3 3 4 3 4]"

numbers = s[1:-1].split() # a list of strings
print(numbers)
numbers = [int(n) for n in numbers] # a list of integers
print(numbers)

Prints:

['3', '3', '4', '3', '4']
[3, 3, 4, 3, 4]

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