Pro-Fun Pro-Fun - 1 month ago 9
Python Question

how to count output and make newline every 7 characters?

I just learned the basics of Python , when searching google for cool thing to do with Python found this pdf : Binary_Image
(converting 1/0 to * and spaces) this pdf has a Challenge section which say's

"Modify your program so that it has a display width of 6 characters. You could create a new variable
called “position”, and add 1 to it for every character the user enters, printing a “newline” whenever
the position reaches 6."

what I understood of challenge is making a variable to count

img_out
then every 6 characters making a newline

what I don't understood is how to use the "position" variable so i tried this code

#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)


when compile the code with
cmd /k
using
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()


if anyone can help me with how to solve this chalange that's will be great
thanks in advance

P.S : I use Python 3.5.2 on Windows

Answer

Change:

if len(img_out) >= "7":
        img_out = img_out + "\n"

To:

if len(img_out) >= 7:
        img_out = img_out + "\n"

UPDATE:

#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)

In your code, you were just testing if the string was longer then 7, and of course when that was checked for more than one time it would break the line. On my code, i'm testing if the position on the string is divisble by 7, with that every time the seventh character is written it will break a line. I'm also using replace because '\n' is character and can't be counted when i'm doing this.

You can check more about modulus here and about replace here.

Comments