2024-04-23 22:24:56 发布
网友
我尝试从字符串中删除标点符号和数值。我试过以下说法:
name_check = ''.join([letter for letter in name_check if letter not in string.punctuation or not letter.isdigit()])
当我将输入设为tom.alter99999时,它返回完全相同的值,而我希望将值设为tomalter。你知道吗
tom.alter99999
tomalter
只要告诉我我需要在语句中更改什么,以便得到所需的输出。你知道吗
您使用了or条件,这意味着任何给定的字母不是punctuation或不是数字都是真的。你知道吗
or
punctuation
将条件更改为and将起作用。你知道吗
and
name_check = ''.join([letter for letter in name_check if letter not in string.punctuation and not letter.isdigit()])
您还可以使用str.maketrans和音译字符串,将字符串中的所有标点和数字替换为零。你知道吗
str.maketrans
import string translator = str.maketrans('', '', string.punctuation + string.digits) print('tom.alter99999'.translate(translator))
你需要and而不是or
您可以使用re库
re
import re name='tom.alter99999' res = re.findall(r'[a-zA-Z]',name) print("".join(res))
您使用了
or
条件,这意味着任何给定的字母不是punctuation
或不是数字都是真的。你知道吗将条件更改为
and
将起作用。你知道吗您还可以使用
str.maketrans
和音译字符串,将字符串中的所有标点和数字替换为零。你知道吗你需要
and
而不是or
您可以使用
re
库相关问题 更多 >
编程相关推荐