Python 中從字符串中刪除數字


  1. 在 Python 中使用 string.join() 方法中從字符串中刪除數字
  2. 在 Python 中使用 string.translate() 方法從字符串中刪除數字
  3. 在 Python 中使用 re.sub() 方法從字符串中刪除數字

本教程將探討各種方法,以從 Python 中的字符串中刪除數字或數字。在數據清理過程中,我們通常會從自然語言處理中的數據中刪除數字。

假設我們有一個字符串 abcd1234efg567,並且我們想從字符串中刪除數字以得到類似於 abcdefg 的字符串。我們可以使用以下方法從 Python 中的字符串中刪除數字:

在 Python 中使用 string.join() 方法中從字符串中刪除數字

string.join(iterable) 方法將一個可迭代對象 iterable 作為輸入,使用 string 的值作為分隔符將其元素連接在一起,並返回結果字符串作為輸出。

要從字符串中刪除數字,我們將首先遍歷字符串並選擇非數字值,然后將它們傳遞給 string.join() 方法以將它們連接起來,並獲得帶有非數字字符的結果字符串作為輸出。

 

下面的示例代碼演示了如何使用 string.join() 方法從 Python 中的字符串中刪除數字。

 
string = 'abcd1234efg567' newstring = ''.join([i for i in string if not i.isdigit()]) print(newstring) 

輸出:

 
abcdefg

在 Python 中使用 string.translate() 方法從字符串中刪除數字

Python 2 中的 string.translate(map) 方法將映射表或字典作為輸入,並在將指定的字符替換為輸入映射表或字典中定義的字符后返回字符串。

下面的示例代碼演示了如何在 Python 2 中使用 string.translate() 方法從字符串中刪除數字。

 
from string import digits string = 'abcd1234efg567' newstring = string.translate(None, digits) print(newstring) 

輸出:

 
abcdefg

在 Python 3 中,string.translate(table) 將翻譯表作為輸入,而不是像 Python 2 中那樣映射表或字典作為輸入。因此,我們需要使用 str.maketrans() 方法來獲取翻譯表,將其用作 string.translate() 方法的輸入。

 

下面的示例代碼演示了如何在 Python 3 中使用 string.translate() 和 str.maketrans() 方法從字符串中刪除數字:

 
from string import digits string = 'abcd1234efg567' table = str.maketrans('', '', digits) newstring = string.translate(table) print(newstring) 

輸出:

 
abcdefg

在 Python 中使用 re.sub() 方法從字符串中刪除數字

re.sub(pattern, replace, string) 以 string 作為輸入,並通過用 replace 值替換 pattern 字符串(用正則表達式描述)的非重疊出現來返回字符串。在字符串中。

數字的正則表達式為 [0-9]+。我們只需要將其作為 pattern 參數傳遞,並將''作為 replace,就可以使用 re.sub() 方法從輸入 string 中刪除數字。

下面的示例代碼演示了如何使用 re.sub() 方法從字符串中刪除數字:

 
import re string = 'abcd1234efg567' newstring = re.sub(r'[0-9]+', '', string) print(newstring) 

輸出:

 
abcdefg


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM