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?
The easiest is
as @greggo pointed out
string="mystring";
string[:-1]
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.
For a path use os.path.abspath
import os
print os.path.abspath(my_file_path)
You could use String.rstrip
.
result = string.rstrip('/')
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)
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]
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.
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'
Source: Stackoverflow.com