pandas: Extract fields from codes

Product codes such as ABC-123-XL pack a category, a number and a size into one string. Model codes.str.extract(r"^([A-Z]+)-(\d+)-(S|M|L|XL)$").

What to build

A program that splits valid product codes into fields and marks invalid ones.

Requirements

  • A valid code is one or more capital letters, a hyphen, one or more digits, a hyphen, and one of the sizes S, M, L or XL, with nothing before or after.
  • Print code,category,number,size, then one line per code: the code and its three fields, or the code and NaN,NaN,NaN if it is invalid. Keep the number exactly as written (leading zeros stay).
  • Finally print valid K of N.

Input

Line 1: n. Then n codes, one per line.

Output

n + 2 lines.

Constraints

1 ≤ n ≤ 1000; codes contain no commas or spaces.

Example

Input:

4
ABC-123-XL
XY-7-M
bad
Q-12-XXL

Output:

code,category,number,size
ABC-123-XL,ABC,123,XL
XY-7-M,XY,7,M
bad,NaN,NaN,NaN
Q-12-XXL,NaN,NaN,NaN
valid 2 of 4

Why it works

Anchoring the pattern at both ends rejects codes with extra characters, and each capture group becomes one output field, exactly as each group becomes one column in str.extract.

Examples

Example 1 · Input
4
ABC-123-XL
XY-7-M
bad
Q-12-XXL
Expected output
code,category,number,size
ABC-123-XL,ABC,123,XL
XY-7-M,XY,7,M
bad,NaN,NaN,NaN
Q-12-XXL,NaN,NaN,NaN
valid 2 of 4
Example 2 · Input
1
A-1-S
Expected output
code,category,number,size
A-1-S,A,1,S
valid 1 of 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

re.fullmatch(r"([A-Z]+)-(\d+)-(S|M|L|XL)", code) returns a match or None.

Hint 2

match.groups() gives the three captured parts.

Solution

Show one correct solution (try it yourself first)
import re

n = int(input())
pattern = re.compile(r"([A-Z]+)-(\d+)-(S|M|L|XL)")
valid = 0
print("code,category,number,size")
for _ in range(n):
    code = input()
    m = pattern.fullmatch(code)
    if m:
        valid += 1
        print(",".join([code, *m.groups()]))
    else:
        print(code + ",NaN,NaN,NaN")
print(f"valid {valid} of {n}")

Lesson: Working with text columns →