I tried to use input (Py3) /raw_input() (Py2) to get a list of numbers, however with the code
numbers = input()
print(len(numbers))
the input [1,2,3] and 1 2 3 gives a result of 7 and 5 respectively – it seems to interpret the input as if it were a string. Is there any direct way to make a list out of it? Maybe I could use re.findall to extract the integers, but if possible, I would prefer to use a more Pythonic solution.
In Python 3.x, use this.
a = [int(x) for x in input().split()]
Example
>>> a = [int(x) for x in input().split()]
3 4 5
>>> a
[3, 4, 5]
>>>
It is much easier to parse a list of numbers separated by spaces rather than trying to parse Python syntax:
Python 3:
s = input()
numbers = list(map(int, s.split()))
Python 2:
s = raw_input()
numbers = map(int, s.split())
Using Python-like syntax
The standard library provides ast.literal_eval, which can evaluate certain strings as though they were Python code. This does not create a security risk, but it can still result in crashes and a wide variety of exceptions.
For example: on my machine ast.literal_eval('['*1000 + ']'*1000) will raise MemoryError, even though the input is only two kilobytes of text.
As explained in the documentation:
The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis.
(The documentation is slightly inaccurate. ast.literal_eval also supports addition and subtraction of numbers - but not any other operators - so that it can support complex numbers.)
This is sufficient for reading and parsing a list of integers formatted like Python code (e.g. if the input is [1, 2, 3]. For example:
>>> import ast
>>> ast.literal_eval(input("Give me a list: "))
Give me a list: [1,2,3]
[1, 2, 3]
Do not ever use eval for input that could possibly ever come, in whole or in part, from outside the program. It is a critical security risk that enables the creator of that input to run arbitrary code.
It cannot be properly sandboxed without significant expertise and massive restrictions - at which point it is obviously much easier to just use ast.literal_eval. This is increasingly important in our Web-connected world.
In Python 2.x, raw_input is equivalent to Python 3.x input; 2.x input() is equivalent to eval(raw_input()). Python 2.x thus exposed a critical security risk in its built-in, designed-to-be-beginner-friedly functionality, and did so for many years. It also has not been officially supported since Jan 1, 2020. It is approximately as outdated as Windows 7.
Do not use Python 2.x unless you absolutely have to; if you do, do not use the built-in input.
Using your own syntax
Of course, it is clearly possible to parse the input according to custom rules. For example, if we want to read a list of integers, one simple format is to expect the integer values separated by whitespace.
To interpret that, we need to:
Split the string at the whitespace, which will give us a list
Convert strings into integers, and apply that logic to each string in the list.
All of those tasks are covered by the common linked duplicates; the resulting code is shown in the top answer here.
Using other syntaxes
Rather than inventing a format for the input, we could expect input in some other existing, standard format - such as JSON, CSV etc. The standard library includes tools to parse those two. However, it's generally not very user-friendly to expect people to type such input by hand at a prompt. Normally this kind of input will be read from a file instead.
Verifying input
ast.literal_eval will also read and parse many things that aren't a list of integers; so subsequent code that expects a list of integers will still need to verify the input.
Aside from that, if the input isn't formatted as expected, generally some kind of exception will be thrown. Generally you will want to check for this, in order to repeat the prompt. Please see Asking the user for input until they give a valid response.
You can use .split()
numbers = raw_input().split(",")
print len(numbers)
This will still give you strings, but it will be a list of strings.
If you need to map them to a type, use list comprehension:
numbers = [int(n, 10) for n in raw_input().split(",")]
print len(numbers)
If you want to be able to enter in any Python type and have it mapped automatically and you trust your users IMPLICITLY then you can use eval
Another way could be to use the for-loop for this one.
Let's say you want user to input 10 numbers into a list named "memo"
memo=[]
for i in range (10):
x=int(input("enter no. \n"))
memo.insert(i,x)
i+=1
print(memo)
you can pass a string representation of the list to json:
import json
str_list = raw_input("Enter in a list: ")
my_list = json.loads(str_list)
user enters in the list as you would in python: [2, 34, 5.6, 90]
Answer is trivial. try this.
x=input()
Suppose that [1,3,5,'aA','8as'] are given as the inputs
print len(x)
this gives an answer of 5
print x[3]
this gives 'aA'
a=[]
b=int(input())
for i in range(b):
c=int(input())
a.append(c)
The above code snippets is easy method to get values from the user.
Get a list of number as input from the user.
This can be done by using list in python.
L=list(map(int,input(),split()))
Here L indicates list, map is used to map input with the position, int specifies the datatype of the user input which is in integer datatype, and split() is used to split the number based on space.
.
I think if you do it without the split() as mentioned in the first answer. It will work for all the values without spaces. So you don't have to give spaces as in the first answer which is more convenient I guess.
a = [int(x) for x in input()]
a
Here is my ouput:
11111
[1, 1, 1, 1, 1]
try this one ,
n=int(raw_input("Enter length of the list"))
l1=[]
for i in range(n):
a=raw_input()
if(a.isdigit()):
l1.insert(i,float(a)) #statement1
else:
l1.insert(i,a) #statement2
If the element of the list is just a number the statement 1 will get executed and if it is a string then statement 2 will be executed. In the end you will have an list l1 as you needed.
I'm having some issues that I really would like some help on. Right now I'm trying to get the user to input a phone that only accepts the first three things typed in as numbers. The rest can be letters that will get converted into numbers, but even if the first three things are numbers or letters it will keep repeating. The input has to be in this format (XXX-XXX-XXXX).
examples: (234-SDF-SDFL) this would pass, if (SDF-FSD-UEIE) then the program would ask again until the first three are number. Please and thank you.
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
while area.isdigit() == False :
phNumber=input("Number: ")
num=phNumber.split("-")
area=num[0]
Why dont you use regular expressions? (BTW: Do not use this odd naming, use pythons naming convention: snake case)
import re
phone_number=input("Number: ")
while not re.match(r'^\d{3}-[A-Z]{3}-[A-Z]{4}$', phone_number):
phone_number=input("Number: ")
I'm beginner to Python ... I'd like to format the characters in Python using basic concepts and operations of Tuples and Lists as below ...
I enter 10 digit number and except last 4 digits remaining all the numbers should be replaced by 'X'. For e.g.
number = 1234567890
Expecting output as -
number = XXXXXX7890
How to mask entered characters / numbers in Python using Tuples/Lists concept not using by importing any modules or existing high functions. Is it possible ?
For e.g. entered some characters , those should be masked using * (asterisk) or # (hashed) while entering. For e.g.
password : pa55w0rd
Expecting output while entering password as -
password : ********
OR
password: ########
It is always better to use built-in modules for things sensitive like password. One way of doing is following:
import getpass
number = 1234567890
first = 'X' * max(0,len(str(number)[:-4]))
last = str(number)[-4:]
n = first + last
print(n)
# part 2
p = getpass.getpass(prompt='Enter the number : ')
if int(p) == 123:
print('Welcome..!!!')
else:
print('Please enter correct number..!!!')
If you don't want to display typed password just print:
print('######')
It does not have to be of the same length you just have to print something.
Break down what's needed: you need to convert to a string, to figure out how many characters to replace, generate a replacement string of that length, then include the tail of the original string. Also you need to be robust against, eg, strings too short to have any characters replaced.
'X' * max(0, len(str(number)) - 4) + str(number)[-4:]
For the second part: use a library.
Doing this directly is more complicated than it might seem to a beginner, because you're having to communicate with the systems which take text entry. It's going to depend upon the operating system, Windows vs "roughly everything else". For text entry outside of a web-browser or a GUI, most systems are emulating ancient text-only terminal devices because there's not yet enough reason to change that. Those devices have modes of text input (character at a time, line at a time, raw, etc) and changing them to not immediately "echo" the character typed involves some intricate system calls, and then other programming to echo a different character instead.
Thus you're going to want to use a library to take care of all those intricate details for you. Something around password entry. Given the security implications, using tested and hardened code instead of rolling your own is something I strongly encourage. Be aware that there are all sorts of issues around password handling too (constant time comparisons, memory handling, etc) such that as much as possible, you should avoid doing it at all, or move it to another program, and when you do handle it, use the existing libraries.
If you can, stick to the Python standard library and use getpass which won't echo anything for passwords, instead of printing stars.
If you really want the stars, then search https://pypi.org/ for getpass and see all the variants people have produced. Most of the ones I saw in a quick look didn't inspire confidence; pysectools seemed better than the others, but I've not used it.
I am making a discord bot using python.
I have a function
def search(userName):
# ...
but the userName MAY contain spaces
Eg.
Enter userName: Me Head
and I want the function to read bot arguments given and join them together so it forms "MeHead"
Currently if I try to run my search(userName) function with two inputs it will just take the first input so
Enter userName: Me Head
will just run search("Me") and ignore anything after that first input
The input is received is a string, so it does not matter if there are or no spaces. To remove spaces, you must use the function:
str.replace(" ", "")
I want to wrap the colour input in quotes within python:
def main():
colour = input("please enter a colour")
So if I enter red into the input box it automatically makes it "red"
I'm not sure how to do this, would it be something along the lines of:
def main():
colour = """ + input("please enter a colour") + """
Kind regards
The issue is that this doesn't pass syntactically, as Python thinks the second " is the end of the string (the syntax highlighting in your post shows how it's being interpreted). The nicest to read solution is to use single quotes for the string: '"'.
Alternatively, you can escape characters (if you wish to, for example, use both types of quote in a string) with a backslash: "\""
A nice way of doing this kind of insertion of a value, rather than many concatenations of strings, is to use str.format:
colour = '"{}"'.format(input("please enter a colour"))
This can do a lot of things, but here, we are simply using it to insert the value we pass in where we put {}. (Note that pre-2.7, you will need to give the number of the argument to insert e.g: {0} in this case. Past that version, if you don't give one, Python will just use the next value).
Do note that in Python 2.x, you will want raw_input() rather than input() as in 2.x, the latter evaluates the input as Python, which could lead to bad things. In 3.x, the behaviour was fixed so that input() behaves as raw_input() did in 2.x.