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

Question:

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.

Asked By: TaranJS

||

Answers:

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)
Answered By: radiirgummii

Use path lib

from pathlib import Path
fpath = "C:/Program Files/node.js"
   

p = Path(fpath)

print(str(p.parent))

output

C:Program Files
Answered By: Bhargav
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.