How to remove digits from end of a string in Python
Hello programmers, in this tutorial, we will learn how to remove digits from the end of a string in Python.
We can do this using the rstrip([chars]) method.
rstrip([char])
- rstrip reads our string and removes only those character types which we pass a parameter into our method.
- Here [char] is a parameter that specifies which set of characters to be removed.
coding
- For using this
rstrip()
method, we have to 1st import the string library, an inbuilt package in Python. - Here [char] parameter is the digit that we get from
string.digits
which returns digits from zero to nine. - In our string ‘codespeedy123’ there are digits at the end, and we want to remove these three digits so this can be done using the
rstrip(string.digits)
method. - At last, we print our string, and we see there is no digit at the end.
#Importing string library import string #string s='codespeedy123' print("string.digits returns digits 0 to 9: ",string.digits) #removing digits from the end of string using rstrip(string.digits) method s=s.rstrip(string.digits) print("string after removing digits from end: ",s)
output:
string.digits returns digits 0 to 9: 0123456789 string after removing digits from end: codespeedy
Hopefully, you have learned how to remove digits from the end of a string in Python.
Leave a Reply