Last modified: Apr 08, 2023 By Alexander Williams

Python: Remove Number From String With Examples

Using isnumeric() and join()

# define the string with numbers
string_with_numbers = "hello 123 world"

# create a list of characters in the string that are not numeric
no_numbers_list = [char for char in string_with_numbers if not char.isnumeric()]

# join the list back into a string
no_numbers_string = ''.join(no_numbers_list)

# print the result
print(no_numbers_string)

Output:

hello world

Using regular expressions

import re

# define the string with numbers
string_with_numbers = "hello 123 world"

# use regular expressions to substitute all digits with an empty string
no_numbers_string = re.sub(r'\d+', '', string_with_numbers)

# print the result
print(no_numbers_string)

 Output:

hello world

Using translate() and maketrans()

# define the string with numbers
string_with_numbers = "hello 123 world"

# create a translation table with all digits removed
no_numbers_table = str.maketrans('', '', '0123456789')

# use translate() to remove all digits from the string
no_numbers_string = string_with_numbers.translate(no_numbers_table)

# print the result
print(no_numbers_string)

 Output:

hello world

Using nltk

import nltk

# define the string with numbers
string_with_numbers = "hello 123 world"

# tokenize the string into words
words = nltk.word_tokenize(string_with_numbers)

# filter out any words that contain digits
no_numbers_words = [word for word in words if not any(char.isdigit() for char in word)]

# join the remaining words back into a string
no_numbers_string = ' '.join(no_numbers_words)

# print the result
print(no_numbers_string)

 Output:

hello world