Get a Substring From a String in Python
Hello friends, today I will show you how to get a substring from a string in Python. I have used a method called slicing. It uses the index for each character.
Fetch a Substring From a String in Python
The syntax for slicing is:
string[start:end:step]
Here,
- ‘
string
‘ is the variable storing our value. - ‘
start
‘ is the index of the character from where you want to begin the substring. By default, it is 0. - ‘
end
‘ is the index of the last character of the substring from the string. By default, it is the last character’s index. - ‘
step
‘ is the number of index values you want to skip. By default, it is 1
Examples
1 . Let’s take a variable Str
with the value “CodeSpeedy”.
Code :
Str = "CodeSpeedy" Substr = Str[1:8] print(Substr)
As you know indexing starts from 0. In this example, I’ve tried to retrieve a substring from the 1st character to the (8 – 1) i.e. the 7th character.
Output :
odeSpee
2 . Let’s take this situation where I don’t know the end value, then all you need to provide is the starting index.
Code :
Substr = Str[1:] print(Substr)
Here you’ll get the substring value from the the starting index mentioned by you to the last character of the string.
Output :
odeSpeedy
Now you know how to get a substring from a string in Python.
Leave a Reply