-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.

6
  • 4
    uh... print(s[:3])? Commented Apr 29, 2014 at 1:50
  • 1
    @roippi On SO the comments section is not for answers, but for comments. Commented Apr 29, 2014 at 1:54
  • 1
    @SimonT: Seriously? You are scolding him for a concise, accurate answer as a comment??? Commented Apr 29, 2014 at 1:56
  • I'm sorry, I'm afraid I worded the question wrong Commented Apr 29, 2014 at 1:59
  • 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. Commented Apr 29, 2014 at 2:05

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.