-1
def PrintThree(s):

    x = len(s)

    return s[0:3] + x[3:]

I am pretty stuck right now on how to print only certain parts of a string. I am trying to make a code where python will print 3 characters at a time, I am trying to make it so the code prints out the whole string but only shows three characters at a time.

This should work with a string of any length.

user3586691
  • 21
  • 1
  • 2
  • 6
  • 4
    uh... `print(s[:3])`? – roippi Apr 29 '14 at 01:50
  • 1
    @roippi On SO the comments section is not for answers, but for comments. – SimonT Apr 29 '14 at 01:54
  • 1
    @SimonT: Seriously? You are scolding him for a concise, accurate answer as a comment??? – dawg Apr 29 '14 at 01:56
  • I'm sorry, I'm afraid I worded the question wrong – user3586691 Apr 29 '14 at 01:59
  • Yeah, that question you guys considered to be already answered has nothing to do with what, I am asking, again, sorry for the mix up. – user3586691 Apr 29 '14 at 02:02
  • 4
    @SimonT 1) I don't want answers to (very) low-quality questions in my answer history, and 2) I would be shocked if that's the answer to his question because `s[0:3]` literally appears in his example code. Hence, `uh`. I have no idea what's going on here. – roippi Apr 29 '14 at 02:05

2 Answers2

7

I'll try to guess expected result:

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

Output

>>> printThree("somestring")
som
est
rin
g
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
4

Use slicing:

def PrintThree(string):
    return string[:3]

This runs as:

>>> PrintThree('abcde')
'abc'
>>> PrintThree('hello there')
'hel'
>>> PrintThree('this works!')
'thi'
>>> PrintThree('hi')
'hi'
>>> 

In the last example, if the length is less than 3, it will print the entire string.

string[:3] is the same as string[0:3], in that it gets the first three characters of any string. As this is a one liner, I would avoid calling a function for it, a lot of cuntions gets confusing after some time:

>>> mystring = 'Hello World!'
>>> mystring[:3]
'Hel'
>>> mystring[0:3]
'Hel'
>>> mystring[4:]
'o World!'
>>> mystring[4:len(mystring)-1]
'o World'
>>> mystring[4:7]
'o W'
>>> 

Or, if you want to print every three characters in the string, use the following code:

>>> def PrintThree(string):
...     string = [string[i:i+3] for i in range(0, len(string), 3)]
...     for k in string:
...             print k
... 
>>> PrintThree('Thisprintseverythreecharacters')
Thi
spr
int
sev
ery
thr
eec
har
act
ers
>>> 

This uses list comprehension to split the string for every 3 characters. It then uses a for statement to print each item in the list.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76