How to split integer input in python?

血红的双手。 提交于 2020-11-29 23:49:59

问题


If you write like

n = str(input())

n = n.split()

print(n)

That will work. But if you try to do it with integers, you will get

`Value Error`.

How to do it with int type?


回答1:


Do you want to separate several numbers? 1 2 3 -> [1, 2, 3]

n = str(input())
n = n.split()
numbers = [int(i) for i in n]
print(numbers)

Or split a number in numeral? 123 -> [1, 2, 3]

n = str(input())
numbers = [int(i) for i in n]
print(numbers)

Use Nikhil answer, if you want to split a number with delimiters 1%3 -> [1, 3]




回答2:


You can split integer value with following ways..

  1. list comprehension

    n = str(input())
    result = [x for x in n]
    print(result)
    
  1. using list object

     n = str(input())
     result = [x for x in n]
     print(result)
    
  2. using map object

     n = str(input())
     result = list(map(int,n))
     print(result)
    



回答3:


You can do that like this,

n = 567
a = str(n).split(YOUR DELIMITER)

Like if YOUR DELIMITER = 6, Then if i print(a) then i get,

['5', '7']


来源:https://stackoverflow.com/questions/49064817/how-to-split-integer-input-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!