I have written a Python function for some post processing in my text recognition algorithm. It works fine, but it seems to be kind of lengthy and has many if-else-conditions. I am looking for a way to simplify my code:
def postProcessing(new_s): #new_s is a list
import string
new_s=removeFrontLetters(new_s) #This function has to be called first
if all(ch in string.digits for ch in new_s[:4]): #checking if first 4 elements are digits.
if all(ch in string.ascii_letters for ch in new_s[4:5]): #checking if the [4] and [5] are letters
if len(new_s)>=7:
if new_s[6]=='C':
new_s=new_s[:7] #if length>=7 and the [6] =='C' the reversed of the first 7 elements has to be returned.
new_s=list(reversed(new_s))
return(new_s)
else:
new_s=new_s[:6] #if length>=7 but the [6] =!'C' the reversed of the first 6 elements has to be returned.
new_s=list(reversed(new_s))
return(new_s)
else:
new_s=list(reversed(new_s)) #if length<7, the reversed of the given list has to be returned.
return(new_s)
else:
print('not valid') #if the [4] and [5] are not letters, it is not valid
else:
print('not valid') #if the [:4] are not digits, it is not valid
This seems very beginner-level and lengthy. I am a beginner, but I am trying to improve my function. Do you have suggestions?
new_s[4:5]gives you the 5th element only, inside a list.all(ch in string.digits for ch in new_s[:4])is also"".join(new_s[:4]).isdigit()(andall(ch in string.ascii_letters for ch in new_s[4:5])isnew_s[4].isalpha()#if the [4] and [5] are not lettersyou're not testing[5]