I am new to python programming and would like to know how can I easily Remove last character from string in Python?
There are several ways to remove last character from string in Python take a look below at each:
You can simply slice the string from start to the last before element.
name = 'qawithexperts' name = name[:-1] print(name) // qawithexpert
In the above code, we are slicing string using Negative index, we can also do slicing using positive Index, here is an example of doing it
string = "qawithexperts" l = len(string) Remove_last = string[:l-1] print(Remove_last)
There is string method
rstrip() in Python, which removes the characters from the right side of the string that is given to it, here is an example
string = "qawithexperts" newString = string.rstrip(string[-1]) print(newString) // qawithexpert
Well this will require you to add more lines of code, but it is just another way, which you can try.
string = "qawithexperts" #length of the string l = len(string) #empty string Final_string = "" #using loop #add the string character by character for i in range(0,l-1): Final_string = Final_string + string[i] print(Final_string)
In above code, we are first measruing string length the using loop, adding characters one by one in new string(Final_string) from main string until l-1, i.e, just before character.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly