How to parse comma-separated integers from user input [duplicate] - python

This question already has answers here:
"pythonic" method to parse a string of comma-separated integers into a list of integers?
(3 answers)
Closed 2 years ago.
I'd like to accept a user input consisting of several comma-separated integers and put them in a list. The values are separated by commas. Let's say I'm giving 100,97,84 as input, the desired output would be [100, 97, 84]. I'm trying the following code:
int(input("Please enter the numbers: "))
but it gives me:
ValueError: invalid literal for int() with base 10: '100,97,84'
What should I do?

input will always return a string, even if it is a digit
If you want a number you write int(input"Enter number :))
I don't know what's the relation between your output and input, however you are looking to enter a list as an input. You can do that by
s = (input("Enter the numbers :"))
numbers = list(map(int, s.split()))
This will return a list in numbers. You enter the numbers with a space in between not a comma
E.g
Enter the numbers :100 97 84
Ouput>>>[100, 97, 84]
If you want them without the brackets and separated by a comma, you can use
print(*numbers, sep=',')
will give
Enter the numbers :100 97 84
Output>>>100,97,84

If you want to write number separated by a comma, first you have to split your input into a list of digit only strings and then map this list through int:
numbers = [int(s) for s in input("Please enter numbers separated by a comma:").split(',')]

Because your phrase contains a comma, put it in a quotation mark to convert it to an integer with the following phrase :
s = (input("Enter the numbers :"))
result = ''.join([i for i in s if i.isdigit()])
print(result)
example
Enter the numbers :12,34
output:
1234
The error problem will be solved

Related

Python, printing multiple string lengths for strings within a list

Using a for loop, how can a list generated by the input function display each string length in the order that they have been input?
example:
Please enter a list of numbers separated by a comma.
one,two,three,four,five
The length of the string one is 3.
The length of the string two is 3.
The length of the string three is 5.
The length of the string four is 4.
The length of the string five is 4.
Below is the code I have written so far. im sure it's laughable but i can't figure it out.
# stringList will contain a list of strings that have been entered.
stringList = input("Please enter a list of numbers seperated by a comma.\ne.g. Citreon,Ford,Audi,Mercedes\n")
i = 0
for i = 0:
print(f"The length of the string {i} is {(len_stringList[])}."
i += 1
I have tried to construct a for loop in order to display the strings in order, along with each strings length.
The string index number should be in text, with index[0] starting at 'one' up to the final user input (five in the example above)
Each string length should be displayed in a numerical value.
Use split to split the input string into a list, and then you can iterate over that list with a for loop and print the len of each element.
>>> for s in input("Please enter a comma-separated list: ").split(","):
... print(f"The length of {s} is {len(s)}")
...
Please enter a comma-separated list: one,two,three,four,five
The length of one is 3
The length of two is 3
The length of three is 5
The length of four is 4
The length of five is 4

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

I want to remove multiple characters from a string input by user [duplicate]

This question already has answers here:
Removing non numeric characters from a string
(9 answers)
Closed 6 years ago.
I am trying to ask the user for their phone number, and many people type their number such as "123-456-7890", "(123)456-7890".
I want to make the program strip the " ()- " from the input so that when I print the number back to the user, it shows it as 1234567980 without all the extra characters.
So far I have been able to remove only the first parentheses from the string by doing this:
number = str(input("Enter phone number: "))
print(number.strip('('))
Strings are iterable, so your problem can be efficiently solved using a list comprehension.
digits = '0123456789'
phone_number = ''.join([x for x in input("Enter phone number: ") if x in digits])
The benefit of this approach is that ONLY digits get included in the final result. Whereas with the replace approach you have to specify each and every exclusion.
Maybe not the most elegant way to do it but:
print(number.replace('(', '').replace(')', '').replace('-', ''))

How do I gather user numerical input into a list in Python?

I'm new to Python and am trying to make a simple program to calculate mean median and mode from numbers input by user. So far I have:
num=[]
UserNumbers=int(input("Enter number sequence separated by spaces: "))
num.append(UserNumbers)
print (num)
I want the user to be able to input multiple int's separated by spaces, however my code only accepts one number. The mean/median/mode part shouldn't be hard as I'm just going to use statistics package in 3.4; just need help with gathering input.
You have to parse the answer if you want it this way.
UserNumbers=input("Enter number sequence separated by spaces: ")
nums = [int(i) for i in UserNumbers.split()]
EDIT:
Duplicate of this question
You can use this one line:
user_numbers = [int(num) for num in raw_input
("Enter number sequence separated by spaces: ").split()]
Notes:
Read about PEP-8
Read about split
List comprehension

Ask a list of integer in python in one line

def entree_liste():
liste_entier = []
liste_nombre = int(input("Enter list of number separate by space :"))
for chiffre in range(liste_nombre):
liste_entier.append(chiffre)
print(liste_entier)
and my error
liste_nombre = int(input("Enter list of number separate by space :"))
ValueError: invalid literal for int() with base 10: '22 33 44 55'
Basically, I am asking the user for a list of int. If I do liste_entier = list(liste_nombre) they count space as an integer and I don't want to have space in my list only the integer.
The function int() will convert a single value to integer. But you have one giant string with many integer values embedded in it. To solve this problem, first split the giant string into a collection (in this case, a list) of smaller strings, each containing only one integer and then convert each of those strings separately.
To perform the splitting operation, you can use the Python string method .split(). That will return a list of strings. Each of those strings can then be converted to integer:
# get list as string
list_nombre = input("Enter list of numbers separated by space:")
# create list of smaller strings, each with one integer-as-string
list_of_int_strings = list_nombre.split(' ')
# convert list of strings to list of integers
list_of_ints = []
for int_string in list_of_int_strings:
list_of_ints.append(int(int_string)
However, in Python we would more concisely write:
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = ([int(s) for s in list_nombre.split(' ')])
liste_entier = list(map(int, input("Enter list of number separate by space :").split()))
As #Larry suggests, this is a reasonable way to write this in Python
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [int(s) for s in list_nombre.split()]
The problem is that it's not possible to handle exceptions inside the list comprehension. To do this, you may want to write your own, more robust/helpful conversion function
def convert_int(s):
try:
return int(s)
except ValueError as e:
print e
return None
list_nombre = input("Enter list of numbers separated by space:")
list_of_ints = [convert_int(s) for s in list_nombre.split()]
What you should do is read in the string, of ints separated by spaces then explode it, and case the entires to int.
input = raw_input("Enter list of number separate by space :")
input.split()
then cast he elements to int
its always safer to read in strings, then deal with the return.
The int() function will only take a string that contains only digits. Since a space is not a digit, it will cause an error. To fix this problem, first split the string into a list of smaller strings, and then convert each of the smaller strings into an integer if possible.
string = input('Enter list of space separated numbers: ')
numbers = [int(n) for n in string.split() if n.isdigit()]

Categories