0

In Python I have a string that looks like this:

str = '1,2,3,4'

I have a method that takes four arguments:

def i_take_four_arguments(a, b, c, d):
  return a + b + c + d

What do I have to do to string to allow it to be sent to the method?

t56k
  • 6,769
  • 9
  • 52
  • 115

2 Answers2

4

If you want to perform arithmetic operation, following is one way. The idea is to convert your split string values to integers and then pass them to the function. The * here unpacks the generator into 4 values which are taken by a, b, c and d respectively.

A word of caution: Don't use in-built function names as variables. In your case, it means don't use str

string = '1,2,3,4'


def i_take_four_arguments(a, b, c, d):
    return a + b + c + d

i_take_four_arguments(*map(int, string.split(',')))
# 10
Sheldore
  • 37,862
  • 7
  • 57
  • 71
0
str = '1,2,3,4'
list_ints = [int(x) for x in str.split(',')]

This will give you a list of integers, which can be added, pass them to your function

Barmar
  • 741,623
  • 53
  • 500
  • 612
Katherine
  • 281
  • 1
  • 2
  • 13
  • 1
    This is only the first part of the answer. A list would constitute only a single argument to the function, you'd need `*` to expand the list to 4 separate arguments. – Paul Rooney Apr 30 '19 at 00:48
  • Yeah, I just assumed that the OP wanted to convert the string to numbers, so that they can be passed to a function that does addition. My bad! – Katherine Apr 30 '19 at 01:05