MJames28
MJames28

Reputation: 37

How can I use isalpha() to replace non-alphabetic characters with white spaces?

I'm trying to check and see if every character in a given string is alphabetic. If it isn't, then replace whatever the character is with a blank space. What I have so far is:

def removePunctuation(txt):

    for char in txt:
        if char.isalpha() == False:
            txt.replace(char, " ")
    return txt

I've tested some input but it's not removing anything.

Upvotes: 2

Views: 2300

Answers (3)

Olivier Melançon
Olivier Melançon

Reputation: 22324

Using str.translate and a defaultdict is a good way to approach translation problems.

from collections import defaultdict
from string import ascii_letters

translation = defaultdict(lambda: ' ', str.maketrans(ascii_letters, ascii_letters))

print('Hello.World!'.translate(translation))

Upvotes: 1

Stephen Rauch
Stephen Rauch

Reputation: 49832

The Python Way:

Use join() and a generator expression like:

new_txt = ''.join(c if c.isalpha() else ' ' for c in txt)

Why did my code not work?

The basic problem with your code is that in Python strings are immutable. Which is to say, once they are built, they never change. You can discard them because you are done with them, but you cannot change them. Because of this .replace() does not change txt. What is does do is return a new string with the characters replaced. This is not at all what you want in the loop you have constructed.

Upvotes: 4

dan04
dan04

Reputation: 91179

The minimum change required to make your function work is:

def removePunctuation(txt):
    for char in txt:
        if char.isalpha() == False:
            txt = txt.replace(char, " ")
    return txt

new_txt = removePunctuation(txt)

Strings are immutable, so str.replace does not alter its argument, but returns a new string.

However, Stephen Rauch's one-liner is a more "Python" way of accomplishing this.

def removePunctuation(txt):
    return ''.join(c if c.isalpha() else ' ' for c in txt)

new_txt = removePunctuation(txt)

Upvotes: 0

Related Questions