简体   繁体   中英

How to take user input and convert it to an array using python

How to take an number input from user and split it's digits and use each digit separately

For example If user enters '''4568''' The code should split 4568 into 4,5,6,8

Use a list comprehension over the user input.

values = [int(i) for i in input()]

Note that this code doesn't handles cases where user puts non-digits characters in his input. To deal with this case, you would prefer to write:

values = [int(i) for i in input() if i.isdigit()]

You could map it to int , and convert the map to list .

digits = list(map(int, input()))

If you want to make sure only numbers are accepted add a filter to the input

digits = list(map(int, filter(lambda c: c.isdigit(), input())))

Convert it to string, iterate to string and get each character as an integer.

# Input from the user
inp = input()
digits=[]
for c in str(inp):
   try:
       digit=int(c)
       # Populate the list with the last digit obtained
       digits.append(digit)
   except:
        # I'm assuming you don't need to worry about any other non integer character
        pass
  

Or in one line, BUT pay attention that if any non integer character is present into the input, the map fails :

inp = 1234
digits = list(map(int, list(str(inp)))

Where list(str(inp)) splits the string-converted input in the list of its characters, map applies the transformation to integer to each element of the latter list, eventually the conversion to list return your desired array

EDIT: I was writing the code while the comment were being written. I've now integrated the direct int suggestion to map function

EDIT2: a nitpicky edit to allow for an actual user input instead of a test variable. This does not change the substance at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM