Reputation: 479
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?
Upvotes: 1
Views: 3498
Reputation: 44053
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]
Upvotes: 2
Reputation: 433
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]
Upvotes: 2
Reputation: 1077
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.
Upvotes: 3