user1796600
user1796600

Reputation: 19

Input to individual items in list

I'm currently writing a binary translator in Python. All works well (from number to binary and from binary to number) - there's just one problem. With the binary to a number, I take in an input but have to use a list:

newBinary = []
Code = int(input()) #will receive something like 1001010

using the information from Code, newBinary will have to look something like this:

[1, 0, 0, 1, 0, 1, 0]

I have tried finding a way to convert the input string to individual characters in a list, but have so far been unsuccessful.

Upvotes: 1

Views: 189

Answers (5)

user1796600
user1796600

Reputation: 19

Thanks so much everyone! I ended up using a modified version of MadsY's anwser:

Code=input("Give your Binary code:  ")

Length = len(Code)
Count = 0

while Count < Length:
    Bin[(-1 - len(Code) + Count + 1)] = Code[Count]
    Count = Count + 1

I had not realized String objects also had the [n] property - which I used to put the characters over to a list =)

The program is now finally complete =) (and yes it was an exercise ;))

Upvotes: 0

Mark Amery
Mark Amery

Reputation: 154695

As others have mentioned, if you just want to convert from binary to decimal, then in real life you should just do

>>> int('101', 2)
5

But I'm guessing this is an exercise rather than a real-world problem and that just bypassing the problem by using a built-in function isn't exactly the solution you had in mind when you asked.

You asked for a way to convert a string to a list of characters. The answer is simply:

>>> list('1010101')
['1', '0', '1', '0', '1', '0', '1']

List comprehensions may also help you do what you want to do cleanly and concisely here. For example, to get from a binary string to a list of 1s and 0s as int objects:

>>> [int(char) for char in '10101']
[1, 0, 1, 0, 1]

Upvotes: 0

Sean Vieira
Sean Vieira

Reputation: 159905

int takes a radix and versions of Python 2.6 and greater have a bin function that will return binary representations of numbers:

>>> int("111", 2)
7
>>> bin(7)
'0b111'

Note: If you are using Python 2.N use raw_input - input actually eval's the content it is given.

Upvotes: 2

Mads Y
Mads Y

Reputation: 396

I'm not sure i understand the question or my solution is the best out there, but thry something like this:

newBinary=[]
Code=input()
for n in range(len(Code)):
    newBinary.append(int(Code[n]))

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250941

don't use int() on input, try something like this:

Python 2.x:

>>> strs=raw_input()
1001010
>>> map(int,strs)
[1, 0, 0, 1, 0, 1, 0]

Python 3.x:

>>> strs=input()
1001010
>>> list(map(int,strs))
[1, 0, 0, 1, 0, 1, 0]

Upvotes: 0

Related Questions