Ben Lippincott
Ben Lippincott

Reputation: 21

How do I separate a space-delimited string into multiple variables?

I'm trying to write a program that uses Pascal's triangle to FOIL binomials. Any binomial FOILed using this method will follow a basic pattern. I already have a general idea of what to do, I just need to figure out how to separate a space-delimited string into many ints that are called by variables.

For example, I want to take this input:

pascalInput = raw_input("Type the full row of Pascal's triangle with numbers separated by space: ") 
#say the input is '1 3 3 1'

and put it into the variables:

pascalVal1
pascalVal2
pascalVal3

etc.

I don't know how I would write out how many variables I need or whatever else.

Upvotes: 0

Views: 1113

Answers (3)

smac89
smac89

Reputation: 43206

use map function

print map(int, raw_input("Type the full row of Pascal's triangle with numbers separated by space: ").split())

Upvotes: 0

Andrey Shokhin
Andrey Shokhin

Reputation: 12192

pascalVals = PascalInput.split(' ')

pascalVals - list of strings. For indexing write

some_var = pascalVals[0]

If you need exactly pascalVal1 vars:

for i in len(pascalVals):
    exec('pascalVal' + str(i+1) + ' = pascalVals[' + str(i) + ']')

Upvotes: 0

Hyperboreus
Hyperboreus

Reputation: 32449

It would be more convenient if you stored your values in a list:

pascalVals = raw_input('...').split()

And then access them like this:

pascalVals[0]
pascalVals[1]
pascalVals[2]

If you want integers instead of strings, use:

pascalVals = [int(x) for x in raw_input('...').split()]

Upvotes: 2

Related Questions