Search code examples
pythonpathstrip

How to remove text from a string after a specific character?


My program is like the command prompt (cmd) but much simpler. I am creating a command called, 'bd' which stands for back (one) directory. There is a path string: path = "C:/Program Files/node.js" and I want to remove the last directory '/node.js' but I don't want to use indexing or slicing, because the path string will change on the file's name length.

I have tried path.rstrip("/") but I couldn't figure how to remove the last '/' with the directory name, 'node.js'.

Thanks in advance.


Solution

  • the only way i can think of is to use path.split(/) and reassemble the string afterwards it would look something like this:

    path: str = "C:/Program Files/node.js"
    splitup_path: list = path.split("/")
    new_path: str = ""
    for i in range(path.count("/")):
        new_path += f"{splitup_path[i]}/"
    print(new_path)