Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

return the first four and last four items as a single value.

How do I return the first four and last four items as a single value?

1 Answer

a = "abcdefghijkl"
b = a[0:4] + a[-4:]

Here I have a string called a, variable b is a new string created from slicing and adding the indexes you requested. Does this make sense? First I'm saying give me the first four letters of 'a' which starts at zero and goes to 4 because it doesn't include 4th index. Then I'm adding the last 4 from 'a' by using the negative index which counts from the right. Then by just using : that says give me everything from negative 4 to the end of the string. I hope this helps.

You could also just do this without a new variable.

print(a[0:4] + a[-4:])