如何用python将字符串拆分为2?

Sha*_*han 1 python split python-2.7 python-3.x

我有这些字符串.

"LAKDOER 567-85 06D-1F"
"QRT1 35-43 459-70 D"
"50201 WSCFVGH 133 9H "
"STREE VDERYG 8C LOP"
"GG-STAR THIEOR- WL-515-67-26548H-9"
Run Code Online (Sandbox Code Playgroud)

我想拆分所有字符串,需要像这样的输出.

["LAKDOER", "567-85 06D-1F"]
["QRT1",  "35-43 459-70 D"]
["50201 WSCFVGH", "133 9H "]
["STREE VDERYG", "8C LOP"]
["GG-STAR THIEOR-", "WL-515-67-26548H-9"]
Run Code Online (Sandbox Code Playgroud)

Rom*_*est 5

具有re.split()功能和特定的正则表达式模式:

import re

lst = ["LAKDOER 567-85 06D-1F", "QRT1 35-43 459-70 D", "50201 WSCFVGH 133 9H ", 
       "STREE VDERYG 8C LOP", "GG-STAR THIEOR- WL-515-67-26548H-9"
       ]

pat = re.compile(r'\s(?=[a-z-]*[0-9])', re.I)
for s in lst:
    print(pat.split(s, 1))
Run Code Online (Sandbox Code Playgroud)

输出:

['LAKDOER', '567-85 06D-1F']
['QRT1', '35-43 459-70 D']
['50201 WSCFVGH', '133 9H ']
['STREE VDERYG', '8C LOP']
['GG-STAR THIEOR-', 'WL-515-67-26548H-9']
Run Code Online (Sandbox Code Playgroud)
  • re.I - 正则表达式标志,告诉不匹配大小写
  • \s(?=[a-z-]*[0-9])- 匹配空格字符,\s后跟字符序列,强制数字[0-9]和可选[a-z-]*序列(由正向前瞻断言确保(?=...))