How to Find a Substring of a String in Python 


               


How to Find a Substring of a String in Python



Python


In this article, we show how to find a substring of a string in Python.

This can be done in a few ways.

An example we will do for this article is how to find the file extension of a file name in Python.

Let's say, we have the following file name, Carmelo-anthony-missed-dunk.mp4

How can we write a script in Python that just extracts the file extension (mp4).

We will show how to do this now with the code below.



So in our code, we create a variable called filename that is equal to "Carmelo-anthony-missed-dunk.mp4"

The first thing we do is find the position of the "." in the string in the filename variable.

Once we have found this, we want to get the rest of the string after the period.

Thus, when we create the variable, file_extension, we set it equal to filename[position + 1:]

This will give us the rest of the string from after the period to the end.

Thus, with our string, this returns 'mp4'

Even though Python has built-in functions that could find the file extension of a filename, we were illustrating in general how this could be done with more specialized Python functions.

And this can be done for everything.

It happens to be very useful for filenames because filenames can only have one period in the name and anything after the period has to be the file extension.

If you want to find the file extension with the period included, then you would simply specify, filename[position:]

This will return, '.mp4'

But normally, you would just want the file extension without the dot.

Just to go over another example, let's think of how to get the file name from the string.


Getting the Filename of a Filename String

So before we got the file extension of a filename string.

Now let's get the file name of the string without the extension, just the name.

We're going to use the same exact string as before.

This is shown in the code below.



So now, we extracted just the file name from the string and not the file extension.

So Python is very dynamic in how it can be used in extracting data from a string.

So this shows the importance of the index method in Python and slicing in Python, which allows us to extract whatever data or substring we need to from a string.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...