String formatting and List slicing
Hey there! Welcome back to the Python basics tutorial.
So far we've covered almost 80% of Python basics. However, we didn't look at string formatting and list slicing.
String formatting
When you want to insert variables such as names in the middle of a string, you've:
We have an easier solution. Instead of all that string concatenation, we we can simply leave blank pairs of {} there and use string's format method:
Much better! We can use this to insert multiple variables too.
Or you can name them too.
Cool. Now you have a better way.
f-strings
F-strings were introduced in Python 3.6. They make it incredibly easy to format string.
Even better! You can do simple operations in f-strings too:
You can use % and the type of object you want to insert as well, although f-strings are a better idea:
List Slicing
We know how to access list elements by their index. But if we we want all the items from 3 to 5, we're gonna need some list slicing. To retrieve elements 3 to 5:
List indices, just like ranges are NOT inclusive. Which means, when you do 3:5
you get elements 3 and 4, but not 5. To avoid this, simply do [3:6]
.
Good. Now, if we want we can also get all items of the list after 2 like this:
Till now we put a number after the colon, if we leave it blank, it automatically means "till the end of the list." That means, if you keep the first number blank, it means "from the start of the list" to the next number we specified:
Up to the fourth element. We can also specify steps. To take an element for every two, we do this:
We start at 2, since it's the first (second) element, then we skip one and go to the next, which is 4. Then we go to 6, where we stop. I hope you understood the step thing.
You can slice strings too.
Alright, we've learned slicing lists and formatting strings. Next tutorial we're going to see some more features of Python.
Last updated
Was this helpful?