简体   繁体   中英

Python re.findall with * and **

using a re.findall, is it possible to list two subsequent occurences of * in the same index of the list?

lets say I have str = "2**3 + 2*3" I'd like the list to appear as

lis = re.findall('[\+\-*/()]', str)

lis = [2, **, 3, +, 2, *, 3]

is there some regex like *|** ?

Use + after the char class which repeats the previous token one or more times.

lis = re.findall(r'[-+*/()]+|\d+', string)

or

lis = re.findall(r'[A-Za-z\d]+|[^\w\s]+', string)

Example:

>>> s = "2**3 + 2*3"
>>> re.findall(r'[-+*/()]+|\d+', s)
['2', '**', '3', '+', '2', '*', '3']
>>> re.findall(r'[A-Za-z\d]+|[^\w\s]+', s)
['2', '**', '3', '+', '2', '*', '3']

You may use re.split also,

>>> re.split(r'\s*([-+*/()]+)\s*', s)
['2', '**', '3', '+', '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