Reputation: 828
I have a string which I split in a list on spaces, one of the items in the list is for example, this: "/home/hoeter/PycharmProjects/Renpy/window.py"
The end result I want is to make it come out like this:
window.py="/home/hoeter/PycharmProjects/Renpy/window.py"
In Javascript I would do something like:
var string = "/home/hoeter/PycharmProjects/Renpy/window.py";
for (var i = string.length; i>1; i--)
{
if(string.charAt(i) === "/")
{
temp = string.substring(i+1, string.length);
string = temp + "=" + '"' + string + '"';
console.log(string);
i = 0;
}
}
>>> window.py="/home/hoeter/PycharmProjects/Renpy/window.py"
But for loops don't work this way in Python, I've seen some for loops with enemurate
but I don't understand how I can implement that with what I want.
In the end I want to go through the entire list with for split in splits
and concatenate the results into one string
Upvotes: 0
Views: 2058
Reputation: 14369
The function to properly split the path is os.path.split(path)
. It will make sure the split will be done at the right divider for the OS it runs on.
>>> import os
>>> os.path.split('/home/hoeter/PycharmProjects/Renpy/window.py')
('/home/hoeter/PycharmProjects/Renpy', 'window.py')
>>> os.path.split('/home/hoeter/PycharmProjects/Renpy/window.py')[1]
'window.py'
There is also a convenience function to do it in one step:
>>> os.path.basename('/home/hoeter/PycharmProjects/Renpy/window.py')
'window.py'
Upvotes: 3
Reputation: 7727
You can get everything after the last /
with:
"/home/hoeter/PycharmProjects/Renpy/window.py".split('/')[-1]
Upvotes: 6