0

I'm trying to standardise the user input in this format: dddL where d is a digit and L a capital letter. If the user doesn't add enough digits, I want to fill the missing digits with leading zeroes, if he adds anything else than at most 3 digits and a letter, just reject:

input/standardised example:

input: '1a'
output: '001A'

input: '0a'
output: '000A'

input: '05c'
output: '005C'

input: '001F'
output: '001F' (unchanged)

input: '10x'
output: '010X'

input: '110x'
output: '110X'

My broken attempt right now returns nothing for some reason: (doesn't yet deal with rejecting invalid input)

 >>> x = ['0a', '05c', '001F', '10x']
 >>> [i.upper() if len(i)==4 else ('0' * j) + i.upper() for j in range(4-len(i)) for i in x]
 []

I'm not looking necessarily for list processing, I only want it to work for a single variable as input

confused00
  • 2,556
  • 21
  • 39

2 Answers2

1

For zero padding:

i.zfill(4)

Check invalid input:

import re
re.match("\d{1,3}[A-Z]", i)

Put it together:

[i.zfill(4) for i in x if re.match("\d{1,3}[A-Z]", i)]

Compiling the re separately will make the code faster, so:

x = ['0A', '05C', '001F', '10x']
import re
matcher = re.compile("\d{1,3}[A-Z]")
out = [i.zfill(4) for i in x if matcher.match(i)]
out == ['000A', '005C', '001F']

RE disassembly:

Regular expression visualization

Debuggex Demo

matsjoyce
  • 5,744
  • 6
  • 31
  • 38
  • Thanks for the answer. I accepted the other answer cause Peter DeGlopper already gave me the answer in the comments before, but I appreciate the help. – confused00 Sep 17 '14 at 16:14
1

One implementation:

acceptableInput = re.compile(r"\d{3}[A-Z]")
paddedInput = i.upper().zfill(4)
if acceptableInput.match(paddedInput):
    # do something
else:
    # reject
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83