Python Program - Get a Substring of a String
here's a Python program that gets a substring of a string:
# Define a string string = "Hello, world!" # Get a substring using string slicing substring = string[7:12] # Print the substring print("Substring:", substring)Source:www.theitroad.com
In this program, we define a string called string
("Hello, world!"
).
To get a substring of the string, we can use string slicing, which allows us to extract a portion of a string by specifying a start index and an end index.
In this example, we use string[7:12]
to extract the characters from index 7 (inclusive) to index 12 (exclusive), which corresponds to the substring "world"
.
We assign the result of string[7:12]
to a variable called substring
.
Finally, we print the substring using the print()
function and string formatting.
If we run this program, the output will be:
Substring: world
Note that string slicing can also be used to extract a substring from the beginning or end of a string by omitting the start or end index, respectively. For example, string[:5]
would extract the first 5 characters of the string ("Hello"
), while string[-6:]
would extract the last 6 characters of the string ("world!"
).