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?
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.
number is a python array now?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]