Skip to main content
 首页 » 编程设计

python之如何在 python 中拆分具有多个条件的字符串

2024年11月01日22yxwkf

假设我有一个 pandas 系列 op= SU 3180 和(CMG 3200 或 SU 3210) 我想要这样的输出 ["SU", "3180"] ["CMG", "3200"] ["SU", "3210"]

我的代码是这样的:

if op.str.contains('None').item(): 
    print('No Prereq for this course :) ') 
 
else:  
    string = list() 
    if op.str.contains('or').item(): 
        string=op.str.split('or') 
    if op.str.contains('and').item(): 
        string=op.str.split('and') 
 
    for item in string: 
        print("Pre-req number:",item) 
        for i in item: 
            res=i.split() 
            print(res) 

我得到的输出是这样的 ['SU', '3180'] ['(CMG', '3200', 'or', 'SU', '3210)']

如何修复我的代码?

请您参考如下方法:

Regex可以提供一个简单的解决方案

import re 
 
txt = "op= SU 3180 and (CMG 3200 or SU 3210) " 

创建模式:

reg_exp  = re.compile("([a-zA-Z]{2,3})(\s+\d{4})") 

找到匹配项:

re.findall(reg_exp, txt) 

返回:

[('SU', ' 3180'), ('CMG', ' 3200'), ('SU', ' 3210')]

要构建您的正则表达式,我会推荐 regex101.com