Skip to main content

5.4) Elements Of A String


You can access specific elements of a string; we call this action 'indexing'. Here’s how you do it:
[code lang="python"]
>>> my_string="Hello, World!"
>>> my_string[0]
‘H’
>>> my_string[1]
‘e’
>>> my_string[-1]
‘!’
[/code]
Try it out yourself with a different index value.
Notice that the first element has the index 0. This isn’t necessarily the case in other programming languages, so make sure you remember this.
Here is a diagram which helps you visualise and remember how to select elements of a string with indexing and slicing.


 

The first element of a string is the element 0 and the last element is -1.