我试图从字符串中删除标点符号和数值。我尝试过以下声明:
name_check = ''.join([letter for letter in name_check if letter not in string.punctuation or not letter.isdigit()])
当我将输入作为tom.alter99999
时,它返回完全相同的值,而我希望将值赋予tomalter
。
只需要我在声明中需要更改的内容,以便获得所需的输出。
答案 0 :(得分:3)
您使用了or
条件,这意味着任何给定的字母都不是punctuation
或不是数字,它始终是真的。
将条件更改为and
将有效。
name_check = ''.join([letter for letter in name_check
if letter not in string.punctuation
and not letter.isdigit()])
您也可以使用str.maketrans
并音译您的字符串,替换字符串中的所有标点符号和数字。
import string
translator = str.maketrans('', '', string.punctuation + string.digits)
print('tom.alter99999'.translate(translator))
答案 1 :(得分:1)
您需要and
而不是or
name_check = ''.join([letter for letter in name_check if letter not in string.punctuation or not letter.isdigit()])
答案 2 :(得分:0)
您可以使用re
库
import re
name='tom.alter99999'
res = re.findall(r'[a-zA-Z]',name)
print("".join(res))
答案 3 :(得分:0)
我解决的陈述或条件也是如此。这是我做的:
name_check = ''.join([letter for letter in name_check if not (letter in string.punctuation or letter.isdigit())])
我的输出为:tomalter