[英]statement not getting implemented in python3
I have tried to remove the punctuation and the numeric values from the string. 我试图从字符串中删除标点符号和数值。 I have tried the following statement: 我尝试了以下语句:
name_check = ''.join([letter for letter in name_check if letter not in string.punctuation or not letter.isdigit()])
when I give input as tom.alter99999
, it returns the exactly same value, whereas I expect to give the value as tomalter
. 当我输入为tom.alter99999
,它返回完全相同的值,而我希望将值tomalter
为tomalter
。
Just me what I need to change in the statement so that I get the desired output. 只是我,我需要在语句中进行更改,以便获得所需的输出。
You used an or
conditional, which means that it'll always be true that any given letter is either not punctuation
or not a digit. 您使用了or
有条件的,这意味着任何给定的字母不是punctuation
或数字都将是正确的。
Changing your conditional to an and
will work. 将您的条件更改为and
将起作用。
name_check = ''.join([letter for letter in name_check
if letter not in string.punctuation
and not letter.isdigit()])
You can also use str.maketrans
and transliterate your string, replacing all punctuation and digits in a string with nothing. 您还可以使用str.maketrans
并对字符串进行音译,将字符串中的所有标点符号和数字全部替换为str.maketrans
。
import string
translator = str.maketrans('', '', string.punctuation + string.digits)
print('tom.alter99999'.translate(translator))
您需要and
or
name_check = ''.join([letter for letter in name_check if letter not in string.punctuation or not letter.isdigit()])
You could use the re
library 您可以使用re
库
import re
name='tom.alter99999'
res = re.findall(r'[a-zA-Z]',name)
print("".join(res))
The statement I solved with or condition too. 我也用or条件解决的语句。 Here is what I did: 这是我所做的:
name_check = ''.join([letter for letter in name_check if not (letter in string.punctuation or letter.isdigit())])
I got the output as: tomalter
我得到的输出为: tomalter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.