An index is an integer referencing a specific position in a string’s character sequence.
You can read multiple consecutive characters, or a substring, using slice notation. Slice notation has the form my_str[start:end], which creates a new string whose value contains the characters of my_str from indices start to end - 1.
url = 'https://www.youtube.com/c/Appficial/playlists'domain = url[8:23] # Read ‘youtube.com' from urlprint(domain)
Remember that strings are immutable in Python. Slice notation does not change the string but returns a new string returning the substring character sequence.
You can also add a 3rd argument in your slice notation called the stride, which sets the increment value after reading each element. For example, if it is set to 2, it will read every other character.
numbers = '0123456789'
print(f'All numbers: {numbers[::]}')
print(f'Even numbers: {numbers[::2]}')
print(f'Every 3rd number between 1 and 8: {numbers[1:9:3]}')
Subscribe to Appficial for more programming videos coming soon. Also, don't forget to click LIKE and comment on the video if it helped you out!
0 Comments