-1

all I am very new to Python. I want to receive input integers with possible white spaces. Here is an example.

if I input 1234 I receive [1,2,3,4].
if I input 12 34 I receive [1,2,3,4].
if I input 012 4 I receive [0,1,2,4].

How can I do that? Thank you in advance for the help.

Barney_su
  • 43
  • 6
  • 1
    you should parse the line input – Netwave Sep 01 '17 at 16:13
  • Possible duplicate of [Python - Split user input integer into list, where each entry is 2 digits](https://stackoverflow.com/questions/32882040/python-split-user-input-integer-into-list-where-each-entry-is-2-digits) – Netwave Sep 01 '17 at 16:14

6 Answers6

1
input_string = '1234'
print(list(input_string.replace(' ', '')))

input_string ='12 34'
print(list(input_string.replace(' ', '')))

input_string ='012 4'
print(list(input_string.replace(' ', '')))

OUTPUT:

['1', '2', '3', '4']
['1', '2', '3', '4']
['0', '1', '2', '4']
1

You can test each character as a digit and simultaneously convert to a list of ints:

for s in ('1234','12 34', '1 2 3 4', '012 4'):
    print([int(n) for n in s if n.isdigit()])

Or, use a functional approach:

for s in ('1234','12 34', '1 2 3 4', '012 4'):
    print(map(int,filter(lambda c: c.isdigit(), s)))
dawg
  • 98,345
  • 23
  • 131
  • 206
1

you can receive input like this yourInput = input("Insert your input:")

to check if you have a whitespace you can compare your string with a whitespace " "

inputIntegers = input("Input your Integers with whitespaces:")
output = []
for i in inputIntegers:
    if(i != " "):
        output.append(i)

output is then what you want

Jonas Z
  • 11
  • 3
0
data = '12 34'


data = data.replace(" ", "")
list = []

for d in data:
    list.append(int(d))
print list
Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17
0
import re
re.findall(r'[0-9]','12 34')

['1', '2', '3', '4']

list(map(int, re.findall(r'[0-9]','012 4')))
# To get as integer elements

[0, 1, 2, 4]
Kaushik Nayak
  • 30,772
  • 5
  • 32
  • 45
0
print map(int,''.join("12 3 4".split()))
akp
  • 619
  • 5
  • 12