tags:

views:

60

answers:

3

I'm having trouble printing a string in lines chat contains 60 characters.

my code is below:

s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz'

for i in range(0, len(s), 60):
    for k in s[i:i+60]:
        print k
+4  A: 

s[i:i+60] will slice the 60 characters you want into a string. By adding a second for loop, you're looping over each character in that string and outputting it separately. Just output s[i:i+60] instead

Michael Mrozek
d'oh!! Thanks for the help!!
Craig
+1 for answering first, and correctly
Dolph
+1 for a clearer/beginner-friendly explanation, answering before me, and fixing the typo in my answer :)
sdolan
+4  A: 

Print the slice itself, not each character in the slice.

s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz'

for i in range(0, len(s), 60):
    print s[i:i+60]
sdolan
+1 for showing code
Dolph
+2  A: 

You can also use the textwrap module, ie textwrap.fill(s, 60)

THC4k
+1: I didn't even know about the textwrap module. It is *much* slower though. Testing w/ timeit on 1000 iterations I got the following results: 400 chars- range: 0.83 textwrap: 3.24, 4000 chars- range: .83 ave textwrap: 244.09.
sdolan