简体   繁体   中英

How to convert an integer to a list in python?

I have an integer object for example a = 1234 and I want to convert it to a list, so it would look something like [1234].

I tried converting it into a string first and then converting it to a list but that gives me [1,2,3,4]. Any suggestions?

You can just cover it in brackets.

a = 1234
print([a])

Or append()

b = []
b.append(a)

output

[1234]

If you are trying to convert in to string, use str()

>>> str(1234)
'1234'

If you are trying to put your int in a list, use [] :

>>> var = 1234
>>> [var]
[1234]

or do:

>>> l = []
>>> l.append(var)
>>> l
[1234]

Here:

a = 1234
lst = []
lst.append(a)

print(lst) #[1234]

Just cover it with brackets:

a=1243
a=[a]

or create a list and append a

b = []
b.append(a) # or you could do b=[a]

Just do var = int (input()) var = list(var)

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