我正在编写一个小程序,将字符串转换为整数,然后在字符串列表中转换为二进制.这就是我所拥有的
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语句的冒号上遇到语法错误,我不知道为什么.任何帮助,将不胜感激.
你真正的问题是你在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 ; 这是一个等待发生的安全漏洞.