I have pasted to code in which I have used regex library in python, while to work on regex I typecasted the x and y variable(in individual scripts) as string to work with regex functions but then also I'm unable to use that variable.
import re
field_value="CREDIT MEMO SHHAA00172362/AB2"
field_value=field_value.replace("CREDIT MEMO ","")
x=re.findall("/.*",field_value)
print(x)
if x:
field_value=re.sub(str(x),"",field_value)
print(field_value)
Why is the str type casting is not working on list x?
#Similarly:
import re
field_value='SICR-2205-11-0-00045-1'
y=re.findall('^[A-Z][A-Z][A-Z][A-Z]',field_value)
if y:
print(y)
x=re.split("-",field_value,1)
print(x[0])
print(x[2])
if x[0] == str(y):
print('123')
Why the str type casting is not working on list y?
CodePudding user response:
The method re.findall()
always returns an array, even if it is empty or just contains one element.
So str(y)
becomes the string "['SICR']"
.
If what you actually want to compare is the first match re.findall('^[A-Z][A-Z][A-Z][A-Z]',field_value)
comes up with (in this case, "SICR"
) with x[0]
, then you actually want to do:
if x[0] == y[0]:
print('123')
Since y[0]
is the first match re.findall()
found.