python - How do I convert a string to an array? - Stack Overflow
mysql - How to convert array string to an array in python - Stack Overflow
How to Convert a String to an array in Python? - Stack Overflow
How would you approach transforming this string into an array?
import array as arr
output = arr.array('b', [ord(c) for c in 'abcdef'])
will output
array('b', [97, 98, 100, 101, 102])
Of course, you have to remember to convert back to characters with chr(), whenever you need to use them as letters/strings.
My answer is limited to NumPy array. Try just this:
import numpy as np
array = np.array(list("acb"))
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
You can use literal_eval in the ast module
>>> from ast import literal_eval
>>> s = "['a',['b','c','d'],'e']"
>>> print(literal_eval(s))
['a', ['b', 'c', 'd'], 'e']
If you can convert those single quotes to double quotes, you can use json parsing.
import json
obj1 = json.loads('["a", ["b", "c", "d"], "e"]')
input: s = 'Convert why = x2 + 6x + and into the form why = a(x-h)2 + k. Show your work.'
output: [
'Convert ',
'why = x^2 + 6x + and',
' into the form ',
'why = a(x-h)^2 + k',
'. Show your work.',
]I have a solution based on using a regex lookahead and lookbehind splitting on spaces ... but it is pretty shallow.
I am kind of at a loss as to how to do it with a bit more nuance, and would really appreciate seeing your guys's work.
Thanks.
Like this:
>>> text = 'a,b,c'
>>> text = text.split(',')
>>> text
[ 'a', 'b', 'c' ]
Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future:
>>> word = 'abc'
>>> L = list(word)
>>> L
['a', 'b', 'c']
>>> ''.join(L)
'abc'
But what you're dealing with right now, go with @Cameron's answer.
>>> word = 'a,b,c'
>>> L = word.split(',')
>>> L
['a', 'b', 'c']
>>> ','.join(L)
'a,b,c'
Nice solution, a few suggestions:
- The function name
convert_to_int_arrayseems too general. Consider a more specific name, for example,extract_numbers, or something similar. - There is no need to initialize
results_as_arraytoNone. - Mapping a list of strings to integers:
looks like the job forfor index in range(0, len(results_as_array)): results_as_array[index] = int(results_as_array[index].strip()) return results_as_arraymap:
Since the result ofreturn list(map(int, results_as_array))mapis a generator, it needs to be converted to a list withlist. - Tests: I noticed this line:
testing by changingdraw_result = "04-15-17-25-41" # change to "01-12 + 08-20" or "04-15-17-25-41" or "03-23-27-34-37, Mega Ball: 13" to testdraw_resultmanually it is time-consuming. A better way would be to keep the tests in a dictionary and to useassert. For example:
If you want to explore more "unit testing" have a look at unittest.tests = { "04-15-17-25-41": [4, 15, 17, 25, 41], "01-12 + 08-20": [1, 12, 8, 20], "03-23-27-34-37, Mega Ball: 13": [3, 23, 27, 34, 37] } for lottery_string, expected_output in tests.items(): assert expected_output == convert_to_int_array(lottery_string)
Alternative approach:
- Remove
, Mega Ball: 13if exists - Extract all numbers with a regular expression
import re
def extract_numbers(draw_result):
draw_result = draw_result.split(',')[0]
matches = re.findall(r'\d+', draw_result)
return list(map(int, matches))
Marc's answer is an excellent option if you don't care about validation.
If you need to be somewhat sure that the given string represents one of the known formats, then you can pre-bind a match method in a list of pre-compiled regular expressions:
import re
from typing import Iterable
lottery_searches = [
re.compile(pat).match
for pat in (
r'^(\d+)-(\d+)-(\d+)-(\d+)-(\d+), Mega Ball.*$',
r'^(\d+)-(\d+) \+ (\d+)-(\d+)$',
r'^(\d+)-(\d+)-(\d+)-(\d+)-(\d+)$',
)
]
def lottery_string_to_ints(lottery: str) -> Iterable[int]:
for search in lottery_searches:
match = search(lottery)
if match:
return (int(g) for g in match.groups())
raise ValueError(f'"{lottery}" is not a valid lottery string')
with output
In[2]: tuple(lottery_string_to_ints('03-23-27-34-37, Mega Ball: 13'))
Out[2]: (3, 23, 27, 34, 37)
In[3]: tuple(lottery_string_to_ints('01-12 + 08-20'))
Out[3]: (1, 12, 8, 20)
In[4]: tuple(lottery_string_to_ints('04-15-17-25-41'))
Out[4]: (4, 15, 17, 25, 41)
In[5]: tuple(lottery_string_to_ints('04-15'))
Traceback (most recent call last):
File "262933.py", line 20, in lottery_string_to_ints
raise ValueError(f'"{lottery}" is not a valid lottery string')
ValueError: "04-15" is not a valid lottery string