-4

I am trying to print out three characters of a string at a time. I am aware of

>>> s = 1234
>>> s[0:3]
123 

I need the whole string to print but only three characters to be displayed at a time.

This is what I am being asked. Write a function PrintThree(s) that prints out a string s, three characters at a time. Remember that len(s) returns the length of a string.

I just need to be guided on how to do so, if you just post a code, please give a brief explanation, thanks!

emesday
  • 6,078
  • 3
  • 29
  • 46
user3586691
  • 21
  • 1
  • 2
  • 6
  • 2
    You should have edited your previous question rather than posting a new one. Also, I still don't understand what you're asking. Provide *example output*. – roippi Apr 29 '14 at 02:10
  • I'm just trying to study for a Final, my professor gave us a list of scenarios and we have to figure out how to write a code for each. This is one of them. No, we don't have any examples of this particular problem. This is the last problem and the way that he asked the question is written exactly in my question. – user3586691 Apr 29 '14 at 02:20
  • @xbb Thanks for helping I believe that is what I needed. I appreciate your help and lack of trolling. – user3586691 Apr 29 '14 at 02:23

3 Answers3

3

Assume I understand correctly, it looks like this:

def PrintThree(s):
    for i in range(0,len(s),3):
        print s[i:i+3]

>>> PrintThree('abcd')
    abc
    d

>>> PrintThree('abgdag')
    abg
    dag
xbb
  • 2,073
  • 1
  • 19
  • 34
0

there are lots of ways to accomplish your objective. I am going to go with the most direct

def printThrees(mystring):
    s = ''                # we are going to initialize an empty string
    count  = 0            # initialize a counter
    for item in mystring:  # for every item in the string
        s+=item            #add the item to our empty string
        count +=1          # increment the counter by one
        if count == 3:      # test the value
            print s            # if the value = 3 print and reset
            s = ''
            count = 0
   return


mystring = '123abc456def789'
printThrees(mystring)
123
abc
456
def
789
PyNEwbie
  • 4,882
  • 4
  • 38
  • 86
0

I just need to be guided on how to do so

Slice indices are integers.

len(s) will give you the length of a string as an integer.

You can use a for loop to increment an integer.

Matthew Trevor
  • 14,354
  • 6
  • 37
  • 50