What is the fastest way to convert string to array in python?

convert string list to list python
convert string to array python
python split string by character count
convert string to set python
python convert string to list without split
python array to list of strings
convert string to vector python
python split word into letters

This is a line I read from a text file:

[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]

I used readline() to read it in as a string. Now what is the fastest way to convert it back to an array?

Thank you!

I'm not sure that this is the fastest, but it's definitely the safest/easiest:

import ast
lst = ast.literal_eval(s)

regular eval would work too:

lst = eval(s)

Some basic timings from my machine:

>>> s = '[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]' 
>>> def f1():
...    eval(s)
>>> def f2():
...    ast.literal_eval(s)
>>> timeit.timeit('f1()', 'from __main__ import f1')
>>> timeit.timeit('f2()', 'from __main__ import f2')

So, according to my computer, eval is about 50% faster than ast.literal_eval. However, eval is terribly unsafe and should never be used on any string unless you trust it completely. Unless this is a real demonstratable bottleneck and you trust the input 100%, I would consider the little bit of extra time worth it in exchange for being able to sleep soundly at night.

Python, Let's discuss a few ways to convert an array of strings to array of floats. Method #​1 : Using astype. filter_none. edit close. play_arrow. link brightness_4 This is a line I read from a text file: [54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1] I used readline() to read it in as a string. Now what is the fastest way to convert it

Since we care about speed, in this particular case I might use json.loads:

>>> import ast, json
>>> s = "[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]"
>>> %timeit ast.literal_eval(s)
10000 loops, best of 3: 61.6 µs per loop
>>> %timeit eval(s)
10000 loops, best of 3: 45.7 µs per loop
>>> %timeit json.loads(s)
100000 loops, best of 3: 6.61 µs per loop
>>> json.loads(s)
[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]

(Note that this works here because this line is sufficiently JSON-like. It can't be used everywhere that ast.literal_eval can because not all Python literal syntax is valid JSON.)

Python, To do this we use the split() method. Syntax: string.split("delimiter"). Examples: Input : "Geeks for Geeks" Output : ['Geeks'  How to convert a Python csv string to array? Python Server Side Programming Programming Easiest way is to use the str.split method to split on every occurance of ',' and map every string to the strip method to remove any leading/trailing whitespace.

If that's the string, go here http://docs.python.org/2/library/functions.html#eval

>>> s = "[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]"
>>> eval(s)
[54, 95, 45, -97, -51, 84, 0, 32, -55, 14, 50, 54, 68, -3, 57, 88, -1]

Python String split() Method, The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will  import array integerValue = array.array("I", 'y\xcc\xa6\xbb')[0] Warning: the above is strongly platform-specific. Both the “I” specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.

I'm using python 3.6

Here's my result of an actual string separated by spaces

stringValue = "123 456 789 012 345 678"

String to List

intValue = list(map(int, stringValue.split(' ')))


time taken 7.586999345221557e-06

[76, 96, 127, 255, 136, 164]

time taken trying to print it 6.697199933114462e-05

String to List to numpy

intValue = np.array(list(map(int, stringValue.split(' '))))


time taken 2.631999996083323e-05

[ 76 96 127 255 136 164]

time taken trying to print it 0.002241893000245909

String to numpy array

intValue = np.fromstring(stringValue,dtype=int,sep=' ')

time taken 1.3830000170855783e-05

[ 76 96 127 255 136 164]

time taken trying to print it 0.0003395890007595881

How to convert a NumPy array of strings to an array of floats in Python, Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless  Python | Convert list to Python array Sometimes while working in Python we can have a problem in which we need to restrict the data elements to be just of one type. List, can be heterogeneous, can have data of multiple data types and it is sometimes undesirable.

numpy.asarray, Convert the input to an array. Parameters: a : array_like. Input data, in any form that can be  str is a flexible way to represent an integer in a variety of different number systems.. Conclusion. Congratulations! You’ve learned so much about integers and how to represent and convert them between Python string and int data types.

In Python, how do I convert a string to a list in which each character , How do I write a Python program to sum the elements of an array? 1,187 Views · How do I convert string value like 0830 (which means 8:30) into time and add or subtract minutes (ex: 0830 + 15 Protect apps fast, so you don't get hacked. source (Optional) - source to initialize the array of bytes. encoding (Optional) - if source is a string, the encoding of the string. errors (Optional) - if source is a string, the action to take when the encoding conversion fails (Read more: String encoding) The source parameter can be used to initialize the byte array in the following ways:

In Python, how do you convert a list to a string?, By using “”.join(list): It is a string method, and takes a list of things to join with the string. surendra-is-a-good-programmer Unlike in JavaScript , which we can convert an array with mixed types of elements (nonuniform) to string, the join()  Thankfully, Python comes with the built-in module datetime for dealing with dates and times. As you probably guessed, it comes with various functions for manipulating dates and times. Using this module, we can easily parse any date-time string and convert it to a datetime object. Converting Strings Using datetime

  • You have a list, not an array. There are subtle differences...
  • And by far the safest. eval(s) may be the fastest.
  • @JonathonReinhart -- Yeah, seriously. I'm not sure I've ever seen it go up that fast.
  • @mgilson That's what she said.
  • @TimPeters -- You're correct. timeit shows that eval is about 50% faster on my machine.
  • This use of eval is disturbing.
  • Cool! I wouldn't have guessed that - impressive :-)
  • Sure DSM... I post a good answer and then you just have to go and trump it. Kudos to you (and since Kudos aren't an official unit of StackOverflow currency, +1 along with it).
  • I prefer the solution with json as using eval could end terribly wrong.
  • @ᴋᴇʏsᴇʀ , I accept the suggestion, but I disagree on explaining eval. It's there, in the official python docs I posted, and IMHO it's more instructive to go there and read instead of repeating a piece of information here (and it's more "pythonic" too.)
  • I'm not saying it's a bad link :p (it most definitely isn't), I'm just saying you should have at least once sentence of meta-text :)