[英]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. 我已经测试了一些输入,但并未删除任何内容。
Use join()
and a generator expression like: 使用
join()
和一个生成器表达式,例如:
new_txt = ''.join(c if c.isalpha() else ' ' for c in txt)
The basic problem with your code is that in Python strings are immutable. 您的代码的基本问题是Python字符串是不可变的。 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
. 因此,
.replace()
不会更改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. 使用
str.translate
和defaultdict
是解决翻译问题的好方法。
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. 字符串是不变的,所以
str.replace
不会改变其参数,但返回一个新字符串。
However, Stephen Rauch's one-liner is a more "Python" way of accomplishing this. 但是,斯蒂芬·劳赫(Stephen Rauch)的单行代码是完成此操作的一种更“ Python”的方法。
def removePunctuation(txt):
return ''.join(c if c.isalpha() else ' ' for c in txt)
new_txt = removePunctuation(txt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.