-1

Suppose I have a filename ./file and I want to remove the leading ./ (if it starts with ./). What would be the best python way to do this? My take at this is:

if filename.startswith("./"):
  # remove leading ./
  filename = filename[2:]

Isn't there a more elegant way?

PS: it should remove the leading part only if it matches exactly, think of the following filenames:

./filename
.configfile
../file
./.configfile
5
  • new_list = [element.replace("./", "") for element in old_list] Commented Sep 10, 2019 at 13:32
  • See How to remove the left part of a string? Commented Sep 10, 2019 at 13:33
  • 4
    @OlvinRoght That will replace a part of "../" also... Commented Sep 10, 2019 at 13:33
  • @Itay, you can add if element.startswith(".\") if it's needed. It's just quick comment, not an nswer, feel the deffierence Commented Sep 10, 2019 at 13:41
  • 1
    You can simply use regex: re.sub(r'^./', '', file) Commented Sep 10, 2019 at 13:42

6 Answers 6

1
filenames = ['.configfile', './file1', './dir/file2']
filenames = [fn[2:] if fn.startswith("./") else fn for fn in filenames]

borrowing from your idea but doing it in one line

Sign up to request clarification or add additional context in comments.

Comments

1

My personal preference would be the solution by @user1443098 But for completnes - using re

import re

pattern = re.compile(r'^\./')
files = ['./filename', '.configfile', '../file']
new_files = [re.sub(pattern, '', fname) for fname in files]
print(new_files)

Comments

0

The way you do it is the ways it's usually done. Of course, you can always move it into a function:

def remove_prefix(s, prefix):
    if s.startswith(prefix):
        s = s[len(prefix):]
    return s

Comments

0

I would consider writing a helper function:

def strip_prefix(s, prefix):
  if s.startswith(prefix):
    return s[len(prefix):]
  else:
    return s

print(strip_prefix('./filename', './'))
print(strip_prefix('.configfile', './'))
print(strip_prefix('../file', './'))

Comments

-1

Assuming you are using python3, the best way to deal with paths is trough the pathlib module:

if you only want the filename

from pathlib import Path
paths = ["./filename", ".configfile", "../file"]
only_filenames = [Path(f).name for f in paths]

1 Comment

This is not what the question asks, only exact matches to ./ should be removed, something like ../ should stay the same. Nowhere is stated that only the filename is wanted
-3
if filename.startswith("./"):
    filename.lstrip("./")

2 Comments

that would mess up ./.configfile
Additionally, this would be a better answer if you explained how the code you provided answers the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.