To create a substring or slice a string in Python you can use the slice syntax. Each character in a Python string has an index, just like items in a list. Here's a visual representation of each letter's index number in the string
Using Python's slice notation you can tell Python which parts of the string you would like to access.
s = "hello" s # select item at index 2: 'l' s[1:3] # select from 1 to 3, excluding 3: 'el' s[1:] # select from 1 until end of string: 'ello' s[:2] # select from 0 to 2, excluding 2: 'he' s[0:5:2] # select from 0 to 4, skip every 2nd letter: 'hlo' # use - to select from right to left s[-2] # select 2nd last item: 'l' s[-2:] # select last 2 items: 'lo' s[:-2] # select all but last 2 items: 'hel' s[::-1] # all items, reversed: 'olleh' # Usage example first_two = s[:2] print(first_two) # he
The key points to remember about this notation are that it uses a
[start:stop:skip] pattern, the stop index is excluded from the selection, using a negative index number selects from right to left and setting setting skip to -1 will reverse the string.
Finally, if the above is a bit unclear, here's an example of how you can assign results of the above examples to a variable:
s = 'hello' last_four = s[-4:] print(last_four) # ello