在Python中列出comprehension和ord()以删除除字母之外的所有其他字符
在本文中,我们将学习一个程序,在该程序中,可以使用列表理解和ord()
Python3.x中的函数的概念删除除字母以外的所有字符。或更早。
算法
1.We Traverse the given string to check the charater. 2.Selection of characters is done which lie in the range of either [a-z] or [A-Z]. 3.Using the join function we print all the characters which pass the test together.
示例
def remchar(input): # checking uppercase and lowercase characters final = [ch for ch in input if (ord(ch) in range(ord('a'),ord('z')+1,1)) or (ord(ch) in range(ord('A'),ord('Z')+1,1))] return ''.join(final) # Driver program if __name__ == "__main__": input = "Tutorials@point786._/?" print (remchar(input))
输出结果
Nhooo
该ord()
函数接受一个字符作为参数,然后返回相应的ASCII值。这使我们可以轻松快速地进行比较。
在这里,我们还实现了列表理解功能,该功能使我们可以过滤列表中所有必需的元素,并借助join函数将它们组合在一起以获得所需的输出。
结论
在本文中,我们学习了如何ord()
在Python中使用列表理解和函数来删除除字母之外的所有字符。