如何将字符串分解为多个组件

Kaw*_*iKx 2 python string

我有一个字符串“ABCAPITAL23JAN140CE”。这是在证券交易所交易的期权的符号。字符串的 ABCAPITAL 部分是公司名称。23 是 2023 年。JAN 是月份。140 是执行价格,CE 是期权类型。

所有这些组件可能因不同的选项而异。

我需要一个函数,使得pieces_of_string = splitstring('ABCAPITAL23JAN140CE')

其中 返回pieces_of_string = ['ABCAPITAL', 23, 'JAN', 140, 'CE']

我怎么做?

The*_*ird 9

您可以使用 re.findall 与[A-Z]+|\d+

在regex101上查看此处的匹配项

import re
print(re.findall(r"[A-Z]+|\d+", "ABCAPITAL23JAN140CE"))

# Or converting to int
print([int(v) if v.isdigit() else v for v in re.findall(r"[A-Z]+|\d+", "ABCAPITAL23JAN140CE")])
Run Code Online (Sandbox Code Playgroud)

输出

['ABCAPITAL', '23', 'JAN', '140', 'CE']
['ABCAPITAL', 23, 'JAN', 140, 'CE']
Run Code Online (Sandbox Code Playgroud)

另一种选择是 4 个捕获组匹配数字和月份的缩写部分,例如JAN FEB等等......

^(\S*?)(\d+)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(\d+)(\S+)$
Run Code Online (Sandbox Code Playgroud)

查看regex101上的捕获组匹配

import re
m = re.match(r"(\S*?)(\d+)(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(\d+)(\S+)$", "ABCAPITAL23JAN140CE")
if m:
    print(list(m.groups()))
Run Code Online (Sandbox Code Playgroud)

输出

['ABCAPITAL', '23', '140', 'CE']
Run Code Online (Sandbox Code Playgroud)