-4

I'm writing a small program to convert a string to an integer and then to binary within a list of strings. This is what I have

x=0
while x < len(list):
    list[x]=bin(eval(list[x])
    if(list[x].startswith("0b")):
        list[x]=list[x].replace("0b","")

I am getting a syntax error on the colon of the if statement, I'm not sure why. Any help would be appreciated.

1 Answers1

7

Your real problem is that you were missing a parens at the end of your bin() call.

x = 0
while x < len(list):
    list[x] = bin(eval(list[x]))
    if list[x].startswith("0b"):
        list[x] = list[x].replace("0b","")

You can remove the parens on your if line; python does not use parens around if test suites.

Better not to use built-in type names for variables, so list is a bad name for a variable. And if you want to strip off characters at the start of a string, you can use indexing:

list[x] = list[x][2:]

Presumably your code was not yet complete or you haven't discovered this yet due to the error, but your loop will never end as you are not incrementing x.

Last but not least: do not use eval; it is a security hole waiting to happen.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 6
    And do not use variables named "list". – Scharron May 25 '12 at 15:13
  • 3
    The first statement of this answer is a stylistic comment rather than the actual problem; nevertheless it is right. :) – Sven Marnach May 25 '12 at 15:15
  • The real problem is the missing `)` in the `bin` call .. rest is good and valuable advice, so perhaps that might be a better first line for the answer. – Levon May 25 '12 at 15:36