Simple:
my_str = "abcdefghij"
my_str = my_str[:-1]
Try the following code snippet to better understand how it works by casting the string as a list:
str1 = "abcdefghij"
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
In case, you want to accept the string from the user:
str1 = input("Enter :")
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
To make it take away the last word from a sentence (with words separated by whitespace like space):
str1 = input("Enter :")
list1 = str1.split()
print(list1)
list2 = list1[:-1]
print(list2)
Answer from Cyrille on Stack OverflowSimple:
my_str = "abcdefghij"
my_str = my_str[:-1]
Try the following code snippet to better understand how it works by casting the string as a list:
str1 = "abcdefghij"
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
In case, you want to accept the string from the user:
str1 = input("Enter :")
list1 = list(str1)
print(list1)
list2 = list1[:-1]
print(list2)
To make it take away the last word from a sentence (with words separated by whitespace like space):
str1 = input("Enter :")
list1 = str1.split()
print(list1)
list2 = list1[:-1]
print(list2)
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
5 Ways You Can Remove Last Character From String in Python
regex - How can I remove the last character of a string in python? - Stack Overflow
How to remove last two characters from strings under a Dataframe column
Why is the list method which returns all but the last element named init?
Just some observations:
-
head,tail,init,lastare all four-character words -
Haskell uses these same operations
-
Erlang also seems to use these terms
-
Okasaki's book/thesis also contains these, language is Standard ML
Scala borrowing from these functional languages (particularly ML and Haskell), my guess is the terminology was inspired from these.
More on reddit.comHow do I remove the last character from a Python string?
Can Python strings be changed in place?
How do I remove only a trailing newline?
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.