列表解析和Python中的ord()用于移除除字母以外的所有字符
在本文中,我们将了解一个在Python 3.x或更早版本中利用列表解析和ord()函数可以移除除字母以外所有字符的程序。
算法
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))输出
Tutorialspoint
ord()函数接受一个字符作为参数,并返回对应的ASCII值。这使我们能够进行简单快速的比较。
这里我们还实现了列表解析,它允许我们过滤一个列表的所有必要元素,并将它们与join函数结合起来,得到所需的输出。
结论
在本文中,我们了解了如何使用Python中的列表解析和ord()函数来移除除字母以外的所有字符。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP