Advertisement
Femn0X

Cool program I made

Dec 25th, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | Spirit | 0 0
  1. import re
  2.  
  3. def calculate_numbers_in_braces(string):
  4.   """
  5.  Calculates the sum of all numbers within curly braces {} in a given string.
  6.  
  7.  Args:
  8.    string: The input string.
  9.  
  10.  Returns:
  11.    The sum of all numbers found within curly braces.
  12.  """
  13.  
  14.   numbers_str = re.findall(r'\{([^}]+)\}', string)
  15.   total = 0
  16.   for num_str in numbers_str:
  17.     try:
  18.       numbers = [int(x) for x in num_str.split(',')]
  19.       total += sum(numbers)
  20.     except ValueError:
  21.       print(f"Error: Invalid number format in '{num_str}'")
  22.   return total
  23.  
  24. # Example usage:
  25. string = "{1,2,3}"
  26. result = calculate_numbers_in_braces(string)
  27. print(result)  # Output: 6
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement