列表解析和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