简体   繁体   中英

How to insert character into a list before specific character from the end of the list and the same after last character?

I have a generated list for simple calculator. It looks like this for example:

l = [1,5, +, 2, 7, *, 3, 5, - , 9, 5, +, 4,5,6]

And in the input line it will be looking like this "15 + 27 * 35 - 95 + 456".

What I need to do is to implement a function which makes last entry negative and in parentheses (-456) ( not last digit 6, but all digits after non digit character from the end of the list)

So I have a list

list = [1,5, +, 2, 7, *, 3, 5, -, 9, 5, +, 4, 5, 6]

And I need to insert parentheses after "+" from the end, then "-", then 4,5,6, then parentheses again. So my new list should look like this:

list2 = [1, 5, +, 2, 7, *, 3, 5, - , 9, 5, +, (,-,4,5,6,)] 

Basically I need to find non digit character from the end, insert two characters "(", "-", then add ")" after last digit.

How can I do this?

then I'll apply this function ''.join(map(str,list)) and it will look like this "15 + 27 * 35 - 95 + (-456)"

I've tried to use regex, but seems like I've failed :-(

thanks

Use regular expressions:

formula = "15 + 27 * 35 - 95 + 456"
new_formula = re.sub(r"(\d+)$", r"(-\1)", formula)

Please do not use list as name variable, as there is built-in list function. You might use re module as already noted, but if you do not wish to use it you might harness str method rsplit :

formula = '15 + 27 * 35 - 95 + 456'
parts = formula.rsplit(' + ',1) # note spaces around +
print(parts) # ['15 + 27 * 35 - 95', '456']
output = parts[0] + ' + (-' + parts[1] + ')'
print(output) # 15 + 27 * 35 - 95 + (-456)

2nd argument of rsplit is number of cuts, here 1 , ie split at last ' + ' inside formula . This gives list with 2 str s, which then I concatenate using + operator.

EDIT: As noted there might be something other than + , but we can use harness fact that there are spaces following way:

formula = '15 + 27 * 35 - 95 * 456'
parts = formula.rsplit(' ',2)
print(parts) # ['15 + 27 * 35 - 95', '*', '456']
output = parts[0] + ' ' + parts[1] + ' (-' + parts[2] + ')'
print(output) # 15 + 27 * 35 - 95 * (-456)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM