1. def process_strings(strings, func):
  2. """
  3. Processes a list of strings, handling potential failures gracefully.
  4. Args:
  5. strings: A list of strings to process.
  6. func: A function that takes a string as input and returns a result.
  7. It may raise an exception.
  8. Returns:
  9. A list containing the results of applying the function to each string.
  10. If a string causes an error, the corresponding element in the result
  11. list will be None.
  12. """
  13. results = []
  14. for s in strings:
  15. try:
  16. result = func(s) # Attempt to apply the function
  17. results.append(result)
  18. except Exception:
  19. results.append(None) # Handle exceptions by appending None
  20. return results
  21. if __name__ == '__main__':
  22. # Example usage:
  23. def example_function(s):
  24. """Example function that might fail for certain strings."""
  25. if 'error' in s:
  26. raise ValueError(f"Error processing string: {s}")
  27. return s.upper()
  28. string_list = ["hello", "world", "error string", "python"]
  29. processed_strings = process_strings(string_list, example_function)
  30. print(processed_strings)

Add your comment