1

Check the below code.

extensionsToCheck = ['ALL QTRLY PAYMENTS', 'ATC', 'TL INTEREST', 'TL LIBOR INT']
url_string = "DCA INVESTMENT TL LIBOR INT"
if any(ext in url_string for ext in extensionsToCheck):
  print(url_string)
  print(ext)

I want the value of ext variable value, but I am not able to get this value. I am getting the following error:

NameError: name 'ext' is not defined

How can I access the ext variable in if loop? Is there any way to get the ext variable value in if loop?

Allan
  • 12,117
  • 3
  • 27
  • 51
Akshay
  • 49
  • 8

1 Answers1

1

You might need to change a bit your logic since any will return you a boolean indicating if the condition you are checking is satisfied at least for one element in the list extensionsToCheck:

extensionsToCheck = ['ALL QTRLY PAYMENTS', 'ATC', 'TL INTEREST', 'TL LIBOR INT']
url_string = "DCA INVESTMENT TL LIBOR INT"
extensions = []
for ext in extensionsToCheck:
    if ext in url_string:
        # in this block you have access to
        # the variable ext that satisfy your condition
        extensions.append(ext)

print(extensions) # ['TL LIBOR INT']

The extensions will be in the list extensions if you want to print the first extension that was found use extensions[0].

You can also use the following alternative:

extensionsToCheck = ['ALL QTRLY PAYMENTS', 'ATC', 'TL INTEREST', 'TL LIBOR INT']
url_string = "DCA INVESTMENT TL LIBOR INT"
extensions = [ext for ext in extensionsToCheck if ext in url_string]
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228