def process_strings(strings, func):
"""
Processes a list of strings, handling potential failures gracefully.
Args:
strings: A list of strings to process.
func: A function that takes a string as input and returns a result.
It may raise an exception.
Returns:
A list containing the results of applying the function to each string.
If a string causes an error, the corresponding element in the result
list will be None.
"""
results = []
for s in strings:
try:
result = func(s) # Attempt to apply the function
results.append(result)
except Exception:
results.append(None) # Handle exceptions by appending None
return results
if __name__ == '__main__':
# Example usage:
def example_function(s):
"""Example function that might fail for certain strings."""
if 'error' in s:
raise ValueError(f"Error processing string: {s}")
return s.upper()
string_list = ["hello", "world", "error string", "python"]
processed_strings = process_strings(string_list, example_function)
print(processed_strings)
Add your comment