Skip to content

How to Sum The Strings in Python

The challenge

Create a function that takes 2 nonnegative integers in form of a string as an input, and outputs the sum (also as a string):

Example: (Input1, Input2 –>Output)

"4", "5" --> "9" "34", "5" --> "39"
Code language: Python (python)


  • If either input is an empty string, consider it as zero.
  • Inputs and the expected output will never exceed the signed 32-bit integer limit (2^31 - 1)

The solution in Python code

Option 1:

def sum_str(a, b): return str(int(a or ) + int(b or ))
Code language: Python (python)

Option 2:

def sum_str(*values): return str(sum(int(s or '0') for s in values))
Code language: Python (python)

Option 3:

def sum_str(*args): return str(sum(map(lambda x: int(x) if x else , args)))
Code language: Python (python)

Test cases to validate our solution

import test from solution import sum_str @test.describe("Fixed Tests") def basic_tests():"Sample Tests") def sample_tests(): test.assert_equals(sum_str("4","5"), "9") test.assert_equals(sum_str("34","5"), "39")"Tests with empty strings") def empty_string(): test.assert_equals(sum_str("9",""), "9", "x + empty = x") test.assert_equals(sum_str("","9"), "9", "empty + x = x") test.assert_equals(sum_str("","") , "0", "empty + empty = 0")
Code language: Python (python)

See also  How to Sort an Integer in Python
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x