0

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

2
  • Why don't for loops work this way? for i in range(len(str)-1,1,-1): Commented Feb 23, 2017 at 8:27
  • Re: window.py=... Do you have an object named window with an attribute py? I'm not sure I understand. Commented Feb 23, 2017 at 8:45

2 Answers 2

6

You can get everything after the last / with:

"/home/hoeter/PycharmProjects/Renpy/window.py".split('/')[-1]
Sign up to request clarification or add additional context in comments.

Comments

3

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.