简体   繁体   中英

How to split the string into 2 with python?

I am having these strings.

"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"

I want to split all the strings and need output like this.

["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"]

With re.split() function and specific regex pattern:

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))

The output:

['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']

  • re.I - regex flag, tells to match case-insensitively
  • \\s(?=[az-]*[0-9]) - matches whitespace character \\s followed by character sequence with mandatory number(s) [0-9] and optional [az-]* sequence (ensured by positive lookahead assertion (?=...) )

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