33

I have a file path as a string and trying to remove the last '/' from the end.

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/'

I've been trying it with regex but it just keeps removing all the '/'. Is there any easier way to just remove the last character without regex?

hygull
  • 7,880
  • 2
  • 40
  • 46

8 Answers8

43

The easiest is

as @greggo pointed out

string="mystring";
string[:-1]
sarath joseph
  • 2,415
  • 2
  • 19
  • 23
38

As you say, you don't need to use a regex for this. You can use rstrip.

my_file_path = my_file_path.rstrip('/')

If there is more than one / at the end, this will remove all of them, e.g. '/file.jpg//' -> '/file.jpg'. From your question, I assume that would be ok.

Alasdair
  • 278,338
  • 51
  • 534
  • 489
4

Answering the question: to remove the last character, just use:string = string[:-1].

If you want to remove the last '\' if there is one (or if there is more than one):

while string[-1]=='\\':
    string = string[:-1]

If it's a path, then use the os.path functions:

dir = "dir1\\dir2\\file.jpg\\"   #I'm using windows by the way
os.path.dirname(dir)

although I would 'add' a slash in the end to prevent missing the filename in case there's no slash at the end of the original string:

dir = "dir1\\dir2\\file.jpg"
os.path.dirname(dir + "\\")

When using abspath, (if the path isn't absolute I guess,) will add the current working directory to the path.

os.path.abspath(dir)
tglaria
  • 5,338
  • 2
  • 12
  • 17
3

You could use String.rstrip.

result = string.rstrip('/')
joksnet
  • 2,255
  • 15
  • 18
3

For a path use os.path.abspath

import os    
print os.path.abspath(my_file_path)
djangoliv
  • 1,633
  • 11
  • 24
3

The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/'
my_file_path = my_file_path[:-1]
Host0
  • 31
  • 5
1

To remove the last character, just use a slice: my_file_path[:-1]. If you only want to remove a specific set of characters, use my_file_path.rstrip('/'). If you see the string as a file path, the operation is os.path.dirname. If the path is in fact a filename, I rather wonder where the extra slash came from in the first place.

Yann Vernier
  • 14,850
  • 2
  • 25
  • 26
0

No need to use expensive regex, if barely needed then try- Use r'(/)(?=$)' pattern that is capture last / and replace with r'' i.e. blank character.

>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'
SIslam
  • 5,116
  • 1
  • 23
  • 35