如何解决我必须编写代码以识别模式并替换模式吗?
我有一条问题语句,其中有一列模式,如果前四个字节有日期,则应将这四个字节替换为ccyy,其余部分替换为N,零替换为Z
例如。 20190045689
-> CCYYZZNNNNN
如果是空间,我们还需要考虑空间。
66-7830956
-> NN-NNNZNNN
def patternGeneration(string):
x = re.findall("[\s0-9a-zA-Z]",string)
n = len(x)
j = 0
r = re.compile("\A[^(19|20)]")
y = list(filter(r.match,x))
b = len(y)
for i in range(0,b):
if y[i] == "0":
y[i] = 0
elif y[i] == " ":
y[i] = " "
else:
y[i] = "n"
print(convert(y))
for i in range(0,n):
if x[i] == "0":
x[i] = 0
j = j + 1
elif x[i] == " ":
x[i] = " "
j = j + 1
else:
x[i] = "n"
print(convert(x))
str1 = input("enter the string\t")
patternGeneration(str1)
解决方法
#convert to new format
def convert(string):
# check for year
head = string[:4]
tail = string[4:]
if head.isnumeric():
if 1900 <= int(head) <= 2099:
head = "CCYY"
new_string = head + tail
return "".join(["Z" if x == "0" else "N" if x.isnumeric() else x for x in str(new_string)])
sample = "20196705540"
print(convert(sample))
#"CCYYNNZNNNZ"
sample = "66-7830956"
print(convert(sample))
#"NN-NNNZNNN"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。