Using String. The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
Using slicing to remove the last word For this, we slice the string from its start to the starting index of the last word inside the string and then apply the string rstrip() function to remove any whitespaces in the resulting string's end.
Python list | pop() Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.
Use the String. slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
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.
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)
You could use String.rstrip
.
result = string.rstrip('/')
For a path use os.path.abspath
import os
print os.path.abspath(my_file_path)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With