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:

'Hey there ' + name + '.'

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:

'Hey there {}.'.format(name)

Much better! We can use this to insert multiple variables too.

'Hey there {}. You live at {}'.format(name, age)

Or you can name them too.

'Hey {name}, don\'t you live at {address}'.format(name=name, address=addr)

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.

# We need to add an f before the string to make it an f-string
f'Hey {name}, do you live at {address}?'

Even better! You can do simple operations in f-strings too:

f'Two plus two is {2+2}'

You can use % and the type of object you want to insert as well, although f-strings are a better idea:

# "s" means string
'Hey there %s! How are ya?' % name # name has to be a string

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:

>>> people = ['Dave', 'Mike', 'Sam', 'Alice', 'Bob', 'Daniel']
>>> print(people[3:5])
['Alice', 'Bob']
>>>

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

>>> people = ['Dave', 'Mike', 'Sam', 'Alice', 'Bob', 'Daniel']
>>> print(people[3:6])
['Alice', 'Bob', 'Daniel']
>>> 

Good. Now, if we want we can also get all items of the list after 2 like this:

my_list[2:]

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:

>>> people = ['Dave', 'Mike', 'Sam', 'Alice', 'Bob', 'Daniel']
>>> print(people[:4])
['Dave', 'Mike', 'Sam', 'Alice']
>>> 

Up to the fourth element. We can also specify steps. To take an element for every two, we do this:

>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> print(nums[1:7:2]) # 2nd to 8th with a gap of 2
[2, 4, 6]
>>> 

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