One way is to use re.sub, that's my preferred way.

import re
my_str = "hey th~!ere"
my_new_string = re.sub('[^a-zA-Z0-9 \n\.]', '', my_str)
print my_new_string

Output:

hey there

Another way is to use re.escape:

import string
import re

my_str = "hey th~!ere"

chars = re.escape(string.punctuation)
print re.sub('['+chars+']', '',my_str)

Output:

hey there

Just a small tip about parameters style in python by PEP-8 parameters should be remove_special_chars and not removeSpecialChars

Also if you want to keep the spaces just change [^a-zA-Z0-9 \n\.] to [^a-zA-Z0-9\n\.]

Answer from Kobi K on Stack Overflow
🌐
ItSolutionstuff
itsolutionstuff.com › post › python-string-replace-special-characters-with-space-exampleexample.html
Python String Replace Special Characters with Space Example - ItSolutionstuff.com
October 30, 2023 - import re # Declare String Variable myString = "Hello@, This is It-Solution-Stuff.com. This is awesome.!" # Python String Replace Special Characters with Space replaceString = re.sub('[^a-zA-Z0-9 \n\.]', '', myString) print(replaceString)
Discussions

python - I want to replace a special character with a space - Stack Overflow
Arguments meaning of re.sub is ... to replace, ? needs to be escaped as otherwise it has special meaning there, | means: or, so re.sub will look for ? or : or , or /. Second argument is function which return character to be used in place of original substring: space for / and ... More on stackoverflow.com
🌐 stackoverflow.com
Def Function to Remove Special Characters from User Input and Replace with space " "
To remove or replace a bunch of characters from a string you can use the str.translate() function. >>> table = str.maketrans("", "", "!@#$%^&*()?") >>> data = "will I become rich?!" >>> data.translate(table) 'will I become rich' To ignore case you can convert the user input to lowercase using the str.casefold() function. >>> data = "Will I become rich" >>> data.casefold() 'will i become rich' More on reddit.com
🌐 r/learnpython
5
0
August 22, 2024
Special Characters in str.replace()
You need to escape characters that hold special meaning (eg. [] denotes a character group in regex). To escape them (ie. making them behave like normal characters) you put a backslash in front of them: [ -> \[ ] -> \] " -> \" \ -> \\ More on reddit.com
🌐 r/learnpython
6
2
July 24, 2022
python replace space with special characters between strings - Stack Overflow
I would like to replace all spaces between strings with '#' except for the space after the end of string. Example: input=' hello world ' output = '#hello##world' I know using rstrip() I can More on stackoverflow.com
🌐 stackoverflow.com
March 10, 2013
🌐
NiceSnippets
nicesnippets.com › blog › how-to-replace-special-characters-with-space-in-python-string
How to Replace Special Characters with Space in Python String?
March 20, 2023 - Let's get started with how to replace multiple special characters in a string in python. In this example, I will add myString variable with the hello string. Then we will use the sub() function of re library to replace all special characters with space from a string in python.
🌐
TutorialsPoint
tutorialspoint.com › article › python-program-to-replace-the-spaces-of-a-string-with-a-specific-character
Python Program to Replace the Spaces of a String with a Specific Character
In Python, spaces in a string can be replaced with specific characters using the replace() method. The replace() method substitutes all occurrences of a specified substring with a new substring.
🌐
Reddit
reddit.com › r/learnpython › def function to remove special characters from user input and replace with space " "
r/learnpython on Reddit: Def Function to Remove Special Characters from User Input and Replace with space " "
August 22, 2024 -
This is what my module file looks like with my functions, def ignore_function is the one I've created for this particular problem


















import random

# These are my responses I created in a separate file so that my code would
# be more clean

# They are sepeared by positive, neutral, and negative responses
# The last function called magicball_all() just conjoins them and picks a random response

def magicball_pos():
    pos_resp = [
        "It is certain",
        "It is decidedly so",
        "Without a doubt",
        "Yes definitely",
        "You may rely on it",
        "As I see it, yes",
        "Most likely",
        "Outlook good",
        "Yes",
        "Signs point to yes"
    ]
    return (pos_resp)

def magicalball_neut():

    neut_resp = [
        "Reply hazy, try again",
        "Ask again later",
        "Better not tell you now",
        "Cannot predict now",
        "Concentrate and ask again"
    ]
    return (neut_resp)

def magicalball_neg():

    neg_resp = [
        "Don't count on it",
        "My reply is no",
        "My sources say no",
        "Outlook not so good",
        "Very doubtful"
    ]
    return (neg_resp)

def magicball_all():
    all_resp = [
        magicball_pos,
        magicalball_neut,
        magicalball_neg
    ]
    random_func = random.choice(all_resp)
    return random_func()

def ignore_punct(text):
    remove_punc = ["!", ".", ",", "?"]
    new_text = text
    for char in remove_punc:
        new_text = new_text.replace(char, " ")
    return new_text

















This is my actual program file, with the line:
if ask == "will I become rich":
I need it to ignore any capitals as it will not trigger special even
I also need it to ignore for example if you said "WILL I BECOME RICH????" it will not trigger 
or "will I become rich?!" it will not trigger.
So I need it to ignore case sensitivity as well as punctuation. I'm hoping I can make a function
inside of my mod_imp.py folder that way I don't have to clutter my main program. 






















import logging # Allowed me to use logging callbacks
import time    # Allowed me to implement time
import random  # Allowed me to use the 'random' callback
import mod_imp # Allowed me use my personal module import

# This is my logging config 
logging.basicConfig(
    filename="log.txt", # This either makes a file called log.txt or uses log.txt if exists
    level=logging.DEBUG, # Catches errors within logging
    format="%(asctime)s - %(message)s", # This tells the config what I'm needing logged
    datefmt="%m-%d %H:%M" # Formats the timestamps inside the log
)

logger = logging.getLogger() # Used to record the logging messages


# This is the loop for the Magic 8 Ball
while True: # While the loop is true it will continue
    ask = input("Ask a question or say 'exit' or 'bye' to end: ") # Takes user input
    response = random.choice(mod_imp.magicball_all()) # Uses responses from mod_imp and gives randomly generated response
    if  ask == "will I become rich":                   # Instance of asking a different question // Easter Egg
        logger.info("User asked 'will I become rich' and Magic 8 ball replied 'Don't ask questions you don't want the answer to'") # Logs special response
        print("Don't ask questions you don't want the answer to")
    elif ask == "":                                   # Another easter egg
        logger.info("User asked '' Magic 8 ball replied 'Sorry, mind reading is not in my capabilities. Please try again'") # Logs special response
        print("Sorry, mind reading is not in my capabilites. Please try again")
    elif ask.lower() == "exit" or ask.lower() == "bye":  # Tells loop that if 'exit' or 'bye' is enterd in lowercase to end program
        logger.info("User ended program! Magic 8 ball replied 'Thanks for playing! Goodbye!") # Sends info to log that you ended program
        print("Thanks for playing! Goodbye") 
        break  # Breaks out of loop
    else:
        logger.info(f"user asked: '{ask}' Magic 8 ball replied: '{response}'") # This sends all other information to log that doesn't have special condiitons
        print(response) # Prints the random response from mod_imp
🌐
Reddit
reddit.com › r/learnpython › special characters in str.replace()
r/learnpython on Reddit: Special Characters in str.replace()
July 24, 2022 -

I have the following code.

The aim is to remove all special characters from the column of a DataFrame, although it does not matter if all special characters are removed from the DataFrame.

The code i have used is:

words = combined_body_title.title_body.str.split().explode().str.replace("[?.',)(/:!]","", regex=True)

This works until i put in quotation markets or brackets.

I have read the documentation, from that i think i am using it wrong. I should not be trying to change more than one character within the str.replace, but for some reason it still works just not for brackets and quotation marks.

If you could suggest an alternative solution or help me fix this one i would really appreciate it!

Find elsewhere
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to replace spaces in a python string with a specific character
5 Best Ways to Replace Spaces in a Python String with a Specific Character - Be on the Right Side of Change
February 26, 2024 - The split() method separates the string into a list of words, which join() then converges into a single string, interleaved with a specified character. ... This snippet first splits the text string into a list where spaces are the delimiters, and then it uses the join() function to combine the list elements into a new string, inserting underscores between elements. Method 1: replace(). Simple and direct. Most suitable for straightforward replacements. Not suited for more complex patterns. Method 2: List Comprehension. Elegant and Pythonic.
🌐
Quora
quora.com › In-Python-how-do-I-use-the-replace-function-on-strings-to-replace-multiple-characters-e-g-a-space-or-any-special-character-with-the-empty-string-E-g-Tes-ting-replace-only-replaces-the-space-not-the
In Python, how do I use the .replace() function on strings to replace multiple characters, e.g. a space or any special character, with th...
Answer (1 of 4): Why do you ask how to use a function (method) to do something after you’ve already demonstrated to yourself that the function/method doesn’t do that? Perhaps it’s better to describe what you want to accomplish and ask which functions or methods might already exist to ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python regex replace special characters
Python regex replace special characters - Spark By {Examples}
May 31, 2024 - How to replace special characters in Python using regex? As you are working with strings, you might find yourself in a situation where you want to replace
🌐
StrataScratch
stratascratch.com › blog › how-to-replace-a-character-in-a-python-string
How to Replace a Character in a Python String - StrataScratch
October 18, 2024 - They represent white spaces between the words, which are also treated as characters when converting from a string to a list. ... We’ll use the list comprehension to get rid of those blank rows because white space is not a letter. In the code below, the list comprehension iterates over the column letter and replaces the blank spaces (' ') with NaN values.