简体   繁体   中英

How to store everything before and after a special character?

"t1 = 2; a[0] = 1; a[1] = 2; a[t1] = 3;"

In the above string I want to store all variables and constants separately like:

var = ['t1', 'a[0]', 'a[1]', 'a[t1]']

constants = ['2', '1', '2', '3']

Using Regex.

Ex:

import re

s = "t1 = 2; a[0] = 1; a[1] = 2; a[t1] = 3;"
var, constants = [], []
for v, c in re.findall(r"(.+?) = (.+?);", s):
    var.append(v)
    constants.append(c)
print(var)
print(constants)

Output:

['t1', ' a[0]', ' a[1]', ' a[t1]']
['2', '1', '2', '3']

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