Python | Ways to remove numeric digits from given string
Given a string (may contain both characters and digits), write a Python program to remove the numeric digits from string. Let’s discuss the different ways we can achieve this task.
Method #1: Using join and isdigit()
Python3
# Python code to demonstrate # how to remove numeric digits from string # using join and isdigit # initialising string ini_string = "Geeks123for127geeks" # printing initial ini_string print ("initial string : ", ini_string) # using join and isdigit # to remove numeric digits from string res = ''.join([i for i in ini_string if not i.isdigit()]) # printing result print ("final string : ", res) |
Method #2: Using translate and digits
Python3
# Python code to demonstrate # how to remove numeric digits from string # using translate from string import digits # initialising string ini_string = "Geeks123for127geeks" # printing initial ini_string print ("initial string : ", ini_string) # using translate and digits # to remove numeric digits from string remove_digits = str .maketrans(' ', ' ', digits) res = ini_string.translate(remove_digits) # printing result print ("final string : ", res) |
Method #3: Using filter and lambda
Python3
# Python code to demonstrate # how to remove numeric digits from string # using filter and lambda # initialising string ini_string = "akshat123garg" # printing initial ini_string print ("initial string : ", ini_string) # using filter and lambda # to remove numeric digits from string res = "".join( filter ( lambda x: not x.isdigit(), ini_string)) # res = ini_string # printing result print ("final string : ", str (res)) |
Method#4 Using join() and isalpha()
Python3
# Python code to demonstrate # how to remove numeric digits from string # using join and isalpha # initialising string str1 = "Geeks123for127geeks" # printing initial ini_string print ( "initial string : " , str1) # using join and isaplha # to remove numeric digits from string str2 = "".join(x for x in str1 if x.isalpha()) # printing result print ( "final string : " , str2) |
Output
initial string : Geeks123for127geeks final string : Geeksforgeeks
Method#5: Using loop and in
Python3
# Python code to demonstrate # how to remove numeric digits from string # using loop and in # initialising string str1 = "Geeks123for127geeks" # printing initial ini_string print ( "initial string : " , str1) # using loop and in # to remove numeric digits from string num = "1234567890" str2 = "" for i in str1: if i not in num: str2 + = i # printing result print ( "final string : " , str2) |
Output
initial string : Geeks123for127geeks final string : Geeksforgeeks