Yes, you can use a regular expression for this:

import re
output = re.sub(r'\d+', '', '123hello 456world')
print output  # 'hello world'
Answer from Martin Konecny on Stack Overflow
Top answer
1 of 2
11

Try something like below:

import string
import re
import nltk
from nltk.tokenize import TweetTokenizer

tweet = "first think another Disney movie, might good, it's kids movie. watch it, can't help enjoy it. ages love movie. first saw movie 10 8 years later still love it! Danny Glover superb could play"

def clean_text(text):
    # remove numbers
    text_nonum = re.sub(r'\d+', '', text)
    # remove punctuations and convert characters to lower case
    text_nopunct = "".join([char.lower() for char in text_nonum if char not in string.punctuation]) 
    # substitute multiple whitespace with single whitespace
    # Also, removes leading and trailing whitespaces
    text_no_doublespace = re.sub('\s+', ' ', text_nopunct).strip()
    return text_no_doublespace

cleaned_tweet = clean_text(tweet)
tt = TweetTokenizer()
print(tt.tokenize(cleaned_tweet))

output:

['first', 'think', 'another', 'disney', 'movie', 'might', 'good', 'its', 'kids', 'movie', 'watch', 'it', 'cant', 'help', 'enjoy', 'it', 'ages', 'love', 'movie', 'first', 'saw', 'movie', 'years', 'later', 'still', 'love', 'it', 'danny', 'glover', 'superb', 'could', 'play']
2 of 2
0
# Function for removing Punctuation from Text and It gives total no.of punctuation removed also
# Input: Function takes Existing fie name and New file name as string i.e 'existingFileName.txt' and 'newFileName.txt'
# Return: It returns two things Punctuation Free File opened in read mode and a punctuation count variable.


from nltk.tokenize import word_tokenize
import string


def removePunctuation(tokenizeSampleText, newFileName):
    stringPun = list(string.punctuation)

    with open(tokenizeSampleText, "r") as existingFile:
        tokenize_existingFile = word_tokenize(existingFile.read())

    count_pun = 0
    words = []
    for word in tokenize_existingFile:
        if word in stringPun:
            count_pun += 1
        else:
            words.append(word)

    with open(newFileName, "w+") as puncRemovedFile:
        puncRemovedFile.write(" ".join(words))

    with open(newFileName, "r") as file:
        yield file.read(), count_pun


punRemoved, punCount = removePunctuation(
    "Macbeth.txt", "Macbeth-punctuationRemoved.txt"
)
print(f"Total Punctuation : {punCount}")
print(punRemoved)
Discussions

Delete digits in Python (Regex) - Stack Overflow
I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no More on stackoverflow.com
🌐 stackoverflow.com
python - Removing numbers from string - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Removing everything but letters, numbers, and spaces from string
Thank you for everyone's help! I was able to fix the problem with a more efficient approach compared to what I had before. Code is as follows: def remove_punctuation(word): new_word = "" for letter in word: if letter.isalpha() or letter.isdigit() or letter==' ': new_word += letter return new_word print remove_punctuation("He$r2s*hey {Bea%rs 11") More on reddit.com
🌐 r/learnpython
23
15
May 18, 2019
python - Removing punctuation/numbers from text problem - Stack Overflow
I had some code that worked fine removing punctuation/numbers using regular expressions in python, I had to change the code a bit so that a stop list worked, not particularly important. Anyway, now... More on stackoverflow.com
🌐 stackoverflow.com
April 1, 2011
🌐
GeeksforGeeks
geeksforgeeks.org › python-ways-to-remove-numeric-digits-from-given-string
Python | Ways to remove numeric digits from given string - GeeksforGeeks
December 30, 2024 - In this, we perform task of split() to get all words, getting index of K number using index() and list compre ... In Python, removing a substring from a string can be achieved through various methods such as using replace() function, slicing, or regular expressions.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python string remove numbers
Python String Remove Numbers - Spark By {Examples}
May 21, 2024 - How to remove numbers from the string in Python? You can remove numeric digits/numbers from a given string in Python using many ways, for example, by
🌐
GeeksforGeeks
geeksforgeeks.org › python-remove-all-digits-from-a-list-of-strings
Python | Remove all digits from a list of strings - GeeksforGeeks
December 26, 2024 - String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor · 7 min read Python | Split strings and digits from string list · Sometimes, while working ...
🌐
Delft Stack
delftstack.com › home › howto › python › remove numbers from string python
How to Remove Numbers From String in Python | Delft Stack
February 2, 2024 - To remove numbers from the string, we will first iterate through the string and select non-digit values, pass them to the string.join() method to join them and get the resulting string with non-digit characters as output.
🌐
Built In
builtin.com › software-engineering-perspectives › python-remove-character-from-string
How to Remove Characters From a String in Python | Built In
All of the characters matched will be replaced with an empty string. All of the characters except the alphabets and numbers are removed.
🌐
YouTube
youtube.com › watch
How to Remove/Strip Numbers from a String in Python TUTORIAL (Common Python Interview Question) - YouTube
Python tutorial on how to remove numbers/integers/digits from a string.This is a common python interview question.Solution:'.join([i for i in x if not i.isdi...
Published   August 4, 2019
Find elsewhere
🌐
Netlify
michael-fuchs-python.netlify.app › 2021 › 05 › 22 › nlp-text-pre-processing-i-text-cleaning
NLP - Text Pre-Processing I (Text Cleaning) - Michael Fuchs Python
def remove_punctuation_func(text): ''' Removes all punctuation from a string, if present Args: text (str): String to which the function is to be applied, string Returns: Clean string without punctuations ''' return re.sub(r'[^a-zA-Z0-9]', ' ', text) def remove_irr_char_func(text): ''' Removes all irrelevant characters (numbers and punctuation) from a string, if present Args: text (str): String to which the function is to be applied, string Returns: Clean string without irrelevant characters ''' return re.sub(r'[^a-zA-Z]', ' ', text)
🌐
Reddit
reddit.com › r/learnpython › removing everything but letters, numbers, and spaces from string
r/learnpython on Reddit: Removing everything but letters, numbers, and spaces from string
May 18, 2019 -

So basically I have to remove all instances from a string that isn't a letter, number, or space... So far I'm able to remove everything that isn't a letter or space, however, I'm not sure how I would keep numbers for the way I did it.

Any help would be greatly appreciated. My code is as follows:

def remove_punctuation(word):
    
    new_word = ""
    
    for i in range(len(word)):

        for j in range(52):
            if word[i] == alpha[j]:
                new_word += alpha[j]

    return new_word
    
alpha = [' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C',
'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

print remove_punctuation("He$rs*hey {Bea%rs")

Obviously I can't add every number in the list, lol.

🌐
Replit
replit.com › home › discover › how to remove numbers from a string in python
How to remove numbers from a string in Python | Replit
April 13, 2026 - All numeric types—including decimal digits, letter-like numbers, and other numerals—belong to categories that start with 'N'. This makes checking .startswith('N') a reliable way to identify and remove any number. ... text = "Hello123World456" * 1000 # Large string import time start = time.time() result = ''.join(char for char in text if not char.isdigit()) end = time.time() print(f"Processed {len(text)} characters in {end - start:.6f} seconds")
🌐
Analytics Vidhya
analyticsvidhya.com › home › a quick guide to text cleaning using the nltk library
A Quick Guide to Text Cleaning Using the nltk Library
October 21, 2024 - These are removed after tokenizing the text. ... stopwords = nltk.corpus.stopwords.words('english') text = "Hello! How are you!! I'm very excited that you're going for a trip to Europe!! Yayy!" text_new = "".join([i for i in text if i not in string.punctuation]) print(text_new) words = nltk.tokenize.word_tokenize(text_new) print(words) words_new = [i for i in words if i not in stopwords] print(words_new)
🌐
Netlify
michael-fuchs-python.netlify.app › 2021 › 06 › 05 › nlp-text-pre-processing-iv-single-character-removal
NLP - Text Pre-Processing IV (Single Character Removal) - Michael Fuchs Python
For this publication the processed ... Example String. You can download both files from my “GitHub Repository”. import pandas as pd import numpy as np import pickle as pk import warnings warnings.filterwarnings("ignore") from bs4 import BeautifulSoup import unicodedata import re from nltk.tokenize import ...
🌐
HCL GUVI
studytonight.com › python-howtos › remove-numbers-from-string-in-python
HCL GUVI | Learn to code in your native language
Take your tech career to the next level with HCL GUVI's online programming courses. Learn in native languages with job placement support. Enroll now!