How do I get a substring of a string in Python?
To get a substring of a string in Python, you can use the string[start:end]
notation. This will return a new string that is a copy of the original string, starting from the character at the start
index and going up to, but not including, the character at the end
index.
For example:
original_string = "Hello, world!"
substring = original_string[7:12]
print(substring)
This will output the following string:
world
You can also omit the start
or end
index to specify the beginning or end of the string, respectively. For example:
original_string = "Hello, world!"
# Get the first 5 characters
substring = original_string[:5]
print(substring)
original_string = "Hello, world!"
# Get all characters after the 7th character
substring = original_string[7:]
print(substring)
The first example will output Hello
, and the second example will output world!
.
You can also use negative indices to specify the position of a character relative to the end of the string. For example, -1
refers to the last character in the string, -2
refers to the second-to-last character, and so on.
For example:
original_string = "Hello, world!"
# Get the last 5 characters
substring = original_string[-5:]
print(substring)
This will output world!
.