I have a string "42 0"
(for example) and need to get an array of the two integers. Can I do a .split
on a space?
The obvious approach to this problem is a common combination of simple tasks:
- How do I split a string into a list of words?
- How do I parse a string to a float or int?
- How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)?
However, depending on the exact requirements, it can be addressed in other ways. For some cases, the split step may be sufficient on its own. There are other approaches, given in some answers here, to produce different output besides a native Python list
- for example, using the standard library array.array
, or a Numpy array.
Alternately, the problem can be seen as a special case of How to extract numbers from a string in Python? .