Editor settings

General settings

Save settings

Learn to program with Python

Access part of a string #

You can also extract a portion of a string by specifying a start and end index with the syntax [start:end]. This is called slicing.

For example:

my_string = "Hello, World!"
substring = my_string[2:5]
print(substring) # Output: llo
Note that the end index is exclusive, so the character at the end index is not included in the substring.

We could leave out the start or the end of the index as well. By leaving out the starting index, we tell Python to include all the characters from the beginning. And if we leave out the ending index, we tell Python to include all characters until the end of the string.

For example:

my_string = "Hello, World!"
print(my_string[:5]) # Hello
print(my_string[5:]) # , World!
print(my_string[:]) # Hello, World!

Exercise #

  • Change the number within the [] brackets so that the variable hello has the value "Hello"
  • Use both starting and ending indexs.
Output will be displayed here