Home > Enterprise >  How can I split a string in python in the format [Number][Non Number][Number][Non Number] [duplicate
How can I split a string in python in the format [Number][Non Number][Number][Non Number] [duplicate

Time:09-28

I have a set of strings that I would like to split into smaller blocks.

The string is in the format:

60I40J10=14X240P432;

How can I use python to split the string into:

60I 40J 10= 14X 240P 432;

Thank you for your help!

CodePudding user response:

Try this:

>>> st = '60I40J10=14X240P432;'
>>> fnd = re.split('(\d )',st)[1:]
>>> list(map(''.join, zip(fnd[::2],fnd[1::2])))
['60I', '40J', '10=', '14X', '240P', '432;']

>>> print(*map(''.join, zip(fnd[::2],fnd[1::2])))
60I 40J 10= 14X 240P 432;

CodePudding user response:

You could also use a pattern to match 1 or more digits \d followed by 1 or more chars other than a digit or a whitespace char [^\d\s]

For example

import re

str = "60I40J10=14X240P432;"
pattern = r"\d [^\d\s] "

print(re.findall(pattern, str))

Output

['60I', '40J', '10=', '14X', '240P', '432;']

Example using join and space

print(' '.join(re.findall(pattern, str)))

Output

60I 40J 10= 14X 240P 432;

See a Python demo.

  • Related