Feb-23-2021, 02:03 PM
Hi all, and in advance thanks for helping out the Python rookie :)
For my Programming Class I have to create a program that can search for a substring within a list, and print out all in this case 'countries' containing the substring (if any), else print that no country contains that particular substring. Right now I've managed to get the following result with the code below:
Sorry, but Denmark does not contain the substring 'y'.
The substring 'y' was found in the following country: Germany.
Sorry, but Sweden does not contain the substring 'y'.
The substring 'y' was found in the following country: Norway.
Sorry, but Finland does not contain the substring 'y'.
However, I would very much like a result more like:
The substring 'y' was found in the following countries: Germany, Norway.
or if the substring doesn't exist in the list simply:
Sorry, but the substring does not exist in your list.
...is that possible, if so, how? :)
Best regards Chris
For my Programming Class I have to create a program that can search for a substring within a list, and print out all in this case 'countries' containing the substring (if any), else print that no country contains that particular substring. Right now I've managed to get the following result with the code below:
Sorry, but Denmark does not contain the substring 'y'.
The substring 'y' was found in the following country: Germany.
Sorry, but Sweden does not contain the substring 'y'.
The substring 'y' was found in the following country: Norway.
Sorry, but Finland does not contain the substring 'y'.
However, I would very much like a result more like:
The substring 'y' was found in the following countries: Germany, Norway.
or if the substring doesn't exist in the list simply:
Sorry, but the substring does not exist in your list.
...is that possible, if so, how? :)
1 2 3 4 5 6 7 8 |
countries = [ 'Denmark' , 'Germany' , 'Sweden' , 'Norway' , 'Finland' ] countries_lower = {country.lower() for country in countries} substring = 'y' for country in countries: if substring in country.lower(): print ( f "The substring '{substring}' was found in the following country: {country}." ) else : print ( f "Sorry, but {country} does not contain the substring '{substring}'." ) |