Get the summation of numbers in a string list using Python


In Python, we can sum the numbers present in a string list using various methods like using Regular Expressions, using isdigit() and List Comprehension, using Splitting and Joining etc. When working with lists containing strings in Python, it is common to come across situations where you need to extract and sum the numerical values from those strings. This can be particularly useful in situations such as processing data from text files, log files, or web scraping. In this article, we will understand these methods using different example and algorithms.

Algorithm

A general algorithm to find the sum of numbers in a string list using Python is as follows:

  • Define a function that takes a string list as input.

  • Join all elements of the string list into a single string.

  • Apply a pattern or method to extract numerical values from the string.

  • Convert the extracted values into integers.

  • Sum the list of integers.

  • Return the summation as the result.

Method 1:Using Regular Expressions

Regular expressions provide a efficient way to match patterns in strings. By defining a pattern and using the re.findall() function, we can extract all the numerical values from a string list. These values are then converted to integers and summed to obtain the final result.

Syntax

numbers = [int(num) for num in re.findall(pattern, ''.join(string_list))]

Here, a list comprehension [int(num) for num in re.findall(pattern, ''.join(string_list))] is used to convert the matched strings to integers.

Example

In the above example, we have a string_list containing three elements. The sum_numbers() function is called with string_list as the argument. The regular expression pattern r"\d+" matches one or more digits in each element of the list. The matching digits are extracted and converted into integers using a list comprehension. Finally, the sum() function calculates the sum of these numbers.

import re

def sum_numbers(string_list):
    pattern = r"\d+"
    numbers = [int(num) for num in re.findall(pattern, ''.join(string_list))]
    return sum(numbers)

string_list = ['abc123', 'def456', 'ghi789']
print(sum_numbers(string_list))

Output

1368

Method 2:Using isdigit() and List Comprehension

This method uses the isdigit() method, which checks if a character is a digit, combined with list comprehension. By iterating over each character in the string list and filtering out non−digit characters, we can convert the remaining digits to integers. The resulting list is then summed to get the desired summation.

Syntax

numbers = [int(char) for item in string_list for char in item if char.isdigit()]

Here, a list comprehension [int(char) for item in string_list for char in item if char.isdigit()] is used to iterate over each character in each element of string_list. The isdigit() method is used to check if the character is a digit.

Example

In the below example, we have the same string_list as before. The sum_numbers() function is called with string_list as the argument. The list comprehension iterates over each character in each element of string_list. The isdigit() method checks if the character is a digit, and if so, it is converted to an integer. The resulting list of numbers is then summed using the sum() function.

def sum_numbers(string_list):
    numbers = [int(char) for item in string_list for char in item if char.isdigit()]
    return sum(numbers)

string_list = ['abc123', 'def456', 'ghi789']
print(sum_numbers(string_list))

Output

45

Method 3:Using Splitting and Joining

In this method, the elements of the string list are joined into a single string using the join() method. The concatenated string is then split into a list of words. By iterating over each word and filtering out non−digit words, we can convert the remaining words to integers. Finally, the resulting list of numbers is summed to obtain the desired result.

Syntax

numbers = ''.join(string_list).split()
 numbers = [int(num) for num in numbers if num.isdigit()]

Here, the join() method is used to concatenate all elements of string_list into a single string.

The split() method is then applied to the concatenated string to split it into a list of words. A list comprehension [int(num) for num in numbers if num.isdigit()] is used to iterate over each element in the numbers list and convert it to an integer if it consists only of digits.

Example

In the below example, we are using the filter() function with str.isdigit as the filter condition, we can extract only the digits from each item in the string list. Then, we join the filtered digits using ''.join() and convert the resulting string to an integer using int().

def sum_numbers(string_list):
    numbers = [int(''.join(filter(str.isdigit, item))) for item in string_list]
    return sum(numbers)

string_list = ['abc123', 'def456', 'ghi789']
print(sum_numbers(string_list))

Output

1368

Conclusion

In this article, we discussed how we can find the sum of numbers in a string list using different methods in Python. We discussed three methods: using regular expressions (re), utilizing the isdigit() method with list comprehension, and using splitting and joining operations. Each method has its own advantages and can be used depending on the specific requirements of the task.

Updated on: 17-Jul-2023

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements