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)

Notes:

  • 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 0) + int(b or 0))
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 0, 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(): @test.it("Sample Tests") def sample_tests(): test.assert_equals(sum_str("4","5"), "9") test.assert_equals(sum_str("34","5"), "39") @test.it("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)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments