Python one-liner标准化输入字符串

时间:2014-09-17 15:56:50

标签: python list-comprehension

我正在尝试以这种格式标准化用户输入:dddL其中d是数字,L是大写字母。如果用户没有添加足够的数字,我想用前导零填充缺失的数字,如果他添加除了最多3个数字和一个字母以外的任何内容,则拒绝:

输入/标准化示例:

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'

我现在的破坏尝试由于某种原因没有返回任何内容:(还没有处理拒绝无效输入)

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

我不一定要进行列表处理,我只希望它能用于输入单个变量

2 个答案:

答案 0 :(得分:1)

对于零填充:

i.zfill(4)

检查无效输入:

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

把它放在一起:

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

单独编译re会使代码更快,所以:

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反汇编:

Regular expression visualization

Debuggex Demo

答案 1 :(得分:1)

一种实施方式:

acceptableInput = re.compile(r"\d{3}[A-Z]")
paddedInput = i.upper().zfill(4)
if acceptableInput.match(paddedInput):
    # do something
else:
    # reject