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

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.

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()]

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) + ']')

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

Related

Putting multiple numbers from an input into one list

I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement

How can we take more than one input values in python language by using comma or space between two numbers or character

How can we take more than one input values in python language by using comma or space between two numbers or character??
Simply try:
In Python2:
i = raw_input("Whatever:")
u , c= i.split()
In Python3:
i = input("Whatever:")
u ,c = i.split()
Hope this helps :)
try this:
m, n = raw_input().strip().split(" ")
In the above example, the two values need to be input separated by a space.
If you prefer using a comma for whatever reason, change the split(" ") to split(",")
note that the above example is for python2.
For use in python3, change the raw_input() to input()

Python: How to interpret user input as a list (beginner) [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I am trying to write a function that takes a user inputted list, and transforms it into a string that separates each value inside the list with a comma, and the last value in the list with "and". For example, the list ['cats', 'dogs', 'rabbits', 'bats'] would be transformed to: 'cats, dogs, rabbits, and bats'.
My code works if I assign a list to a variable and then pass the variable to my newString function, but if I pass a user input to my function, it will treat every character in the user input as a separate list value.
So my question is, how can I tell Python that I want input() to be read as a list. Is this even possible? I am very new to Python and programming in general, so Lists and Tuples is about as far as I know so far. I am learning dictionaries now. My code is printed below, thanks.
def listToString(aList):
newString = ''
for i in range(len(aList) - 1):
newString += aList[i] + ', '
newString = newString + 'and ' + aList[-1]
return(newString)
spam = list(input())
print(listToString(spam))
input() always gives you just a string.
You can analyze that string depending on how the user is supposed to enter the list.
For example, the user can enter it space separated like 'cats dogs rabbits bats'. Then you do
input_list = input().split()
print(listToString(input_list))
You can also split on , or any delimiter you like.
If you want to read a list literal from user input, use ast.literal_eval to parse it:
import ast
input_list = ast.literal_eval(input()) # or ast.literal_eval(raw_input()) on Python 2
You could build a list from the input and use your current working code to format it as you want.
def get_user_input():
my_list = []
print('Please input one word for line, leave an empty line to finish.')
while True:
word = input().strip()
if word:
my_list.append(word)
else:
break
return my_list

Python String Split Order Wrong

My current code
defname,last_name):
if not isinstance(reg, int) or \
not isinstance(year, int) or \
not isinstance(degree, str) or \
not isinstance(other_name, str) or \
not isinstance(last_name, str) :
print("Invalid string argument")
elif 0<=year<=4:
l.append((reg,year,degree,other_name,last_name))
else: print("Invalid year")
def p
reg,year,degree,other_name,last_name = student.strip().split(" ",4)
reg=int(reg)
year=int(year)
fullName=last_name+ ", " + other_name
thisYear="Year " + str(year)
print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))
how can I do this effectively with the right formats? I am trying to make it so it uses both functions and is checking for valid
Well, for the reason it's printing on that side, that's because of the way you called .split(). Calling it with the 4 will of course restrict it to splitting 4 times. And since it splits from left to right, once it has made its 4th split (ie. after 'Homer'), it will simply return the rest of the string as a whole (ie. 'J Simpson').
If I were you, I would do it like this:
reg,year,degree,*name = student.strip().split(" ")
name = list(reversed(name))
fullname = name[0] + ', ' + ' '.join(name[1:])
Doing *name lets you grab multiple tokens as a list, and then process them however you like.
First off, wouldn't you want it to print Simpson, Homer J?
Secondly, it prints it J Simpson, Homer because this is what your list looks like:[1342347, 2, G401, Homer, J Simpson].
It splits it this way because you told it to split at each space it sees, and to make a maximum of 4 separate strings. It doesn't know that middle names belong to other_name, so you have to do a little more work in your string parsing to get that to behave as desired.
This is because you are limiting the number of splits to 4.
Thus, for the third line, the 4th space that gets split is between "Homer" and "J". Thus, "J" and "Homer" are in the same string after the split.
https://www.tutorialspoint.com/python/string_split.htm

How to split a variable into two different variables?

For a game that asks input from the user, I am using an if check to determine what the user said. It's for a text based game here, so when a user inputs "examine table" I want examine to become a variable and table to become another variable so I can evaluate them separately in my script.
A variable named "move" is used for the input.
move = input("> ")
I want that variable to split into "action" and "object" variables by splitting the two words in half.
How would I go around doing this?
verb, _, params = move.partition(" ")
verb will be first word
_ will be the separator, whitespace in this case
params will be the rest after the verb
First you want to get the input:
varName = raw_input("Enter anything: ")
Then you want to split the input
splitted_results = varName.split()
print splitted_results
This will give you a list of strings split by empty space. You can loop through as so:
for sr in splitted_results:
print sr
Are you asking how to split a string into 2 different variables?
If so,
string = 'examine table'
splitString = string.split()
giving you the list
['examine','table']
Is it a string? If so, split up the string by whatever character you want to with
string.split("[character to split by here]")
Then, you will get an array. If you only wanted to split by the first character (let's say for example a period):
arr = string.split(".")
arr = [arr[0], ','.join(arr[1:])]

Categories