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?

2
  • 1
    str.split(‘,’) On a different note, don’t use str As your variable names. It’s an inbuilt function Commented Apr 30, 2019 at 0:42
  • 1
    Try: i_take_four_arguments(*str.split(',')) Commented Apr 30, 2019 at 0:42

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

This more than does the trick, thanks so much!
@cd-rum : You’re more than welcome
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

2 Comments

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.
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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.