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.