1

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?

3 Answers 3

3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Does variable number is a python array now?
2

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]

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.