3️⃣

7.3 String Indexing

String Indexing

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:
index:

char:
0

h
1

e
2

l
3

l
4

o
my_string = "hello" print(my_string[2]) # 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.

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.