my_string = "Hello, world!" substring = my_string[7:12]
world
To get a substring of a string in Python, you can use the slicing syntax. This syntax allows you to specify a range of characters to extract from the string, using the start and end indices of the range.
In the example above, the substring variable will contain the characters from the string that are at indices 7 through 12 (not including the character at index 12). The slicing syntax uses the following format: my_string[start:end], where start is the index of the first character to include in the substring, and end is the index of the first character to exclude from the substring.
You can also omit the start or end index if you want to extract the substring from the beginning or end of the string, respectively. Here are some examples:
my_string = "Hello, world!" # get the first 5 characters of the string substring = my_string[:5] # this will return the string "Hello" # get the last 5 characters of the string substring = my_string[-5:] # this will return the string "world"*Note that the slicing syntax always returns a new string that is a copy of the original string. It does not modify the original string.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.