使用Python If语句获取语法错误

-3 python if-statement

我正在编写一个小程序,将字符串转换为整数,然后在字符串列表中转换为二进制.这就是我所拥有的

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

我在if语句的冒号上遇到语法错误,我不知道为什么.任何帮助,将不胜感激.

Mar*_*ers 7

你真正的问题是你在bin()通话结束时错过了一个小伙伴.

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

你可以删除if线路上的parens ; 如果测试套件,python不会使用parens.

最好不要为变量使用内置类型名称,因此变量的名称list不好.如果你想在字符串的开头删除字符,你可以使用索引:

list[x] = list[x][2:]
Run Code Online (Sandbox Code Playgroud)

大概你的代码还没有完成,或者由于错误你还没有发现它,但你的循环永远不会因为你没有递增而结束x.

最后但并非最不重要的:千万不能使用eval ; 这是一个等待发生的安全漏洞.

  • 并且不要使用名为"list"的变量. (6认同)
  • 这个答案的第一个陈述是风格评论而不是实际问题; 尽管如此,这是对的.:) (3认同)