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
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 variablehellohas the value"Hello" - Use both starting and ending indexs.
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules