I have a string such as "12-569-8" and want to split it into a list of negative and positive integers so I can add them together -- such as
list = ['1', '2', '-5', '6', '9', '-8']
where the sum would be 5. I'm mostly struggling with splitting the list.
One possible approach could be to use a regular expression, and match both digits or digits preceded by a negative sign:
s = "12-569-8"
import re
sum(map(int,re.findall(r'(\d|-\d)', s)))
# 5
The other approach, as mentioned by prune in the comments, is looping over the characters and either adding or subtracting based on what you find:
res = 0
i=0
while i < len(s):
x = s[i]
if x != '-':
res += int(x)
else:
i += 1
res -= int(s[i])
i += 1
print(res)
# 5
If you don't want to use an import, you can separate all the characters with a space and remove the space after minus signs. Then split the string on spaces and each number will be correctly interpreted:
s = "12-569-8"
c = " ".join(s).replace("- ","-") # space out, remove space after minus
n = list(map(int,c.split())) # split and convert to integers
print(c) # '1 2 -5 6 9 -8'
print(n) # [1, 2, -5, 6, 9, -8]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.