简体   繁体   中英

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.

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.

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))

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM