I have a string which looks as such:
my_str = '15(1)(635)(634)(582)(583)'
How do I get an array of values from the string?
[15,1,635,634,582,583]
I have a string which looks as such:
my_str = '15(1)(635)(634)(582)(583)'
How do I get an array of values from the string?
[15,1,635,634,582,583]
This can easily be solved with a simple regex : \d+
import re
my_str = '15(1)(635)(634)(582)(583)'
print([int(i.group()) for i in re.finditer(r'\d+', my_str)])
output:
[15, 1, 635, 634, 582, 583]
Remove the ")" and then split on "(":
[int(x) for x in my_str.replace(")", "").split("(")]
This list comprehension also converts the strings to ints.
Given this particular input, one way to simplify the problem is to just grab continguous strings of digits, e.g. using itertools.groupby
:
>>> my_str = '15(1)(635)(634)(582)(583)'
>>> from itertools import groupby
>>> [int(''.join(group)) for dec, group in groupby(my_str, str.isdecimal) if dec]
[15, 1, 635, 634, 582, 583]
You can use the re
module:
import re
my_str = '15(1)(635)(634)(582)(583)'
my_str = re.findall(r"[\w']+", my_str)
for i in range(len(my_str)):
my_str[i] = int(my_str[i])
print(my_str)
This will first split the list into Strings that are separated by special characters, then convert them to ints.
Alternatively, you can use a regular .split()
function to split by "("
, then remove the final ")"
with substring:
my_str = '15(1)(635)(634)(582)(583)'
my_str = my_str.split("(")
for i in range(len(my_str) - 1):
my_str[i + 1] = int(my_str[i + 1][:-1])
my_str[0] = int(my_str[0])
print(my_str)
Output for both:
[15, 1, 635, 634, 582, 583]
I hope this helped! Please let me know if you have any further questions or need clarification :)
This is similar to this one. The preferred solution there was to replace all instances of one of the two delimiters with the other, e.g. by new_str = my_str.replace(')', '(')
, which gives you a string where you have only one kind of brackest as delimiter. Then a .split()
on that with that delimiter, and you get a list, which you can easily convert into an array. If you want the individual values as integers rather than strings you'll also need to cast them.
my_str = '15(1)(635)(634)(582)(583)'
new_str = my_str.replace("(", " ")
new_str = new_str.replace(")", " ")
my_arr = new_str.split()
my_arr = [int(num)for num in my_arr]
print(my_arr)
your str looks like this:
my_str = '15(1)(635)(634)(582)(583)'
so replace ')' by space
mystr = mystr.replace(')'," ")
also replace '(' by space
mystr = mystr.replace(')'," ")
finally:
my_str = "15(1)(635)(634)(582)(583)"
mystr = my_str.replace(")", " ")
mystr = mystr.replace("(", " ")
mystr = [int(x) for x in mystr.split(" ") if x]
mystr