【问题标题】:how to count output and make newline every 7 characters?如何计算输出并每 7 个字符换行一次?
【发布时间】:2017-02-14 07:21:36
【问题描述】:

我刚刚学习了 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

【问题讨论】:

    标签: python io binary


    【解决方案1】:

    变化:

    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' 是字符并且在我这样做时无法计算。

    您可以查看有关模数 here 和替换 here 的更多信息。

    【讨论】:

    • 感谢完美!我会接受答案:) 谢谢
    • 这对我有帮助,但我遇到了另一个小问题:例如。当我输入 111101101110111 时:这应该给我 **** ** *** ** * 第 1 行:4 星空间 2 星第 2 行:空间 3 星空间 2 星第 3 行:星,但它给了第一个 7 1/ 0 和前 7 之后的每个 1/0 将在单行中
    • 如果有办法让编译器计算 7 个字符,然后换行并重复 img_in,如果你可以检查代码,那将是你的好意
    • 编辑以解决您的新问题,希望对您的工作有所帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多