Strings are like lists since they are basically a bunch of characters in a set order.
To retrieve a character at a given index, use the same syntax as if you were retrieving an element from a list:
my_string = "hello" print(my_string) # prints "l"
You can also slice strings the same way you slice lists. For example:
my_string = "hello" print(my_string[2:4]) # prints "ll"
Because strings can be indexed in this way, you can also use a for loop to iterate through each character in a string:
my_string = "hello" for char in my_string: print(char)
The above code prints 'h', 'e', 'l', 'l', and 'o' on their own lines
Also, like before, you can use negative indexes to retrieve characters, starting the count from the back.
my_string = "hello" print(my_string[-1:-3:-1]) # prints "ol"
View code on GitHub.