我刚刚学习了Python的基础知识,当搜索谷歌与Python有关的很酷的事情发现这个pdf:Binary_Image (将1/0转换为*和空格)这个pdf有一个挑战部分,说明了
"修改程序,使其显示宽度为6个字符。您可以创建一个新变量 称为“位置”,并为用户输入的每个字符添加1,每当打印一个“换行符” 这个位置达到了6个。"
我对挑战的理解是使变量计算img_out
然后每6个字符生成一个换行符
我不明白的是如何使用"位置"变量,所以我尝试了这段代码
#get a binary number from the user
img_in = input("Enter your b&w bitmap image :")
#initially, there is no output
img_out = ""
#loop through each character in the binary input
for character in img_in:
#add a star(*) to the output if a 1 is found
if character == "1":
img_out = img_out + "*"
#otherwise, add a space
else:
img_out = img_out + " "
#count the img_out
if len(img_out) >= "7":
img_out = img_out + "\n"
else:
img_out = img_out
#print the image to the screen
print(img_out)
使用cmd /k
python path/to/file.py
编译代码时
Enter your b&w bitmap image :11111101101101
Traceback (most recent call last):
File "C:\Users\saber\Desktop\testing.py", l
if len(img_out) >= "7":
TypeError: unorderable types: int() >= str()
如果有人能帮助我解决这个问题,那将会很棒 提前谢谢
P.S:我在Windows上使用Python 3.5.2
答案 0 :(得分:0)
变化:
if len(img_out) >= "7":
img_out = img_out + "\n"
要:
if len(img_out) >= 7:
img_out = img_out + "\n"
<强>更新强>:
#get a binary number from the user
img_in = input("Enter your b&w bitmap image :")
#initially, there is no output
img_out = ""
#loop through each character in the binary input
for character in img_in:
#add a star(*) to the output if a 1 is found
if character == "1":
img_out = img_out + "*"
#otherwise, add a space
elif character == '0':
img_out = img_out + " "
if len(img_out.replace('\n', '')) % 7 == 0:
img_out = img_out + "\n"
#print the image to the screen
print(img_out)
在你的代码中,你只是测试字符串是否超过7,当然,当检查了多次时,它会破坏该行。在我的代码中,我正在测试字符串上的位置是否可以被7分割,每次写入第七个字符时它都会断开一条线。我也使用替换,因为'\ n'是字符,当我这样做时不能计算。